code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Internal.Log
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports
Partial Friend MustInherit Class AbstractVisualBasicRemoveUnnecessaryImportsService
Inherits AbstractRemoveUnnecessaryImportsService(Of ImportsClauseSyntax)
Public Overrides Async Function RemoveUnnecessaryImportsAsync(
document As Document,
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken) As Task(Of Document)
predicate = If(predicate, Functions(Of SyntaxNode).True)
Using Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_VisualBasic, cancellationToken)
Dim unnecessaryImports = Await GetCommonUnnecessaryImportsOfAllContextAsync(
document, predicate, cancellationToken).ConfigureAwait(False)
If unnecessaryImports.Any(Function(import) import.OverlapsHiddenPosition(cancellationToken)) Then
Return document
End If
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim oldRoot = DirectCast(root, CompilationUnitSyntax)
Dim newRoot = New Rewriter(unnecessaryImports, cancellationToken).Visit(oldRoot)
newRoot = newRoot.WithAdditionalAnnotations(Formatter.Annotation)
cancellationToken.ThrowIfCancellationRequested()
Return document.WithSyntaxRoot(newRoot)
End Using
End Function
Protected Overrides Function GetUnnecessaryImports(
model As SemanticModel, root As SyntaxNode,
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken) As ImmutableArray(Of ImportsClauseSyntax)
predicate = If(predicate, Functions(Of SyntaxNode).True)
Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken)
Dim unnecessaryImports = New HashSet(Of ImportsClauseSyntax)
For Each diagnostic In diagnostics
If diagnostic.Id = "BC50000" Then
Dim node = root.FindNode(diagnostic.Location.SourceSpan)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.Add(DirectCast(node, ImportsClauseSyntax))
End If
End If
If diagnostic.Id = "BC50001" Then
Dim node = TryCast(root.FindNode(diagnostic.Location.SourceSpan), ImportsStatementSyntax)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.AddRange(node.ImportsClauses)
End If
End If
Next
Dim oldRoot = DirectCast(root, CompilationUnitSyntax)
AddRedundantImports(oldRoot, model, unnecessaryImports, predicate, cancellationToken)
Return unnecessaryImports.ToImmutableArray()
End Function
Private Shared Sub AddRedundantImports(
compilationUnit As CompilationUnitSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of ImportsClauseSyntax),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
' Now that we've visited the tree, add any imports that bound to project level
' imports. We definitely can remove them.
For Each statement In compilationUnit.Imports
For Each clause In statement.ImportsClauses
cancellationToken.ThrowIfCancellationRequested()
Dim simpleImportsClause = TryCast(clause, SimpleImportsClauseSyntax)
If simpleImportsClause IsNot Nothing Then
If simpleImportsClause.Alias Is Nothing Then
AddRedundantMemberImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
Else
AddRedundantAliasImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
End If
End If
Next
Next
End Sub
Private Shared Sub AddRedundantAliasImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of ImportsClauseSyntax),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
Dim aliasSymbol = compilation.AliasImports.FirstOrDefault(Function(a) a.Name = clause.Alias.Identifier.ValueText)
If aliasSymbol IsNot Nothing AndAlso
aliasSymbol.Target.Equals(semanticInfo.Symbol) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
End If
End Sub
Private Shared Sub AddRedundantMemberImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of ImportsClauseSyntax),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
If compilation.MemberImports.Contains(namespaceOrType) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
End If
End Sub
End Class
End Namespace
|
weltkante/roslyn
|
src/Features/VisualBasic/Portable/RemoveUnnecessaryImports/AbstractVisualBasicRemoveUnnecessaryImportsService.vb
|
Visual Basic
|
apache-2.0
| 6,752
|
' 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.Text
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders
Friend Module RecommendationHelpers
Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean
Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax
End Function
''' <summary>
''' Returns the parent of the node given. node may be null, which will cause this function to return null.
''' </summary>
<Extension()>
Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode
Return If(node Is Nothing, Nothing, node.Parent)
End Function
<Extension()>
Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean
Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)()
If asNewClause Is Nothing Then
Return False
End If
Dim lastToken As SyntaxToken
Select Case asNewClause.NewExpression.Kind
Case SyntaxKind.ObjectCreationExpression
Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax)
lastToken = If(objectCreation.ArgumentList IsNot Nothing,
objectCreation.ArgumentList.CloseParenToken,
asNewClause.Type.GetLastToken(includeZeroWidth:=True))
Case SyntaxKind.AnonymousObjectCreationExpression
Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax)
lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing,
anonymousObjectCreation.Initializer.CloseBraceToken,
asNewClause.Type.GetLastToken(includeZeroWidth:=True))
Case SyntaxKind.ArrayCreationExpression
Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax)
lastToken = If(arrayCreation.Initializer IsNot Nothing,
arrayCreation.Initializer.CloseBraceToken,
asNewClause.Type.GetLastToken(includeZeroWidth:=True))
Case Else
Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind)
End Select
Return token = lastToken
End Function
<Extension()>
Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean
If objectCreation Is Nothing Then
Return False
End If
Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing,
objectCreation.ArgumentList.CloseParenToken,
objectCreation.Type.GetLastToken(includeZeroWidth:=True))
Return token = lastToken
End Function
<Extension()>
Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean
Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)()
If variableDeclarator Is Nothing Then
Return False
End If
Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _
.Where(Function(oc) oc.Parent IsNot Nothing AndAlso
oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso
variableDeclarator.Initializer IsNot Nothing AndAlso
variableDeclarator.Initializer.Value Is oc) _
.FirstOrDefault()
Return token.IsLastTokenOfObjectCreation(objectCreation)
End Function
<Extension()>
Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean
Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)()
Return token.IsLastTokenOfObjectCreation(objectCreation)
End Function
<Extension()>
Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax
Dim lastJoinCondition = collection.LastOrDefault()
If lastJoinCondition IsNot Nothing Then
Return lastJoinCondition.Right
Else
Return Nothing
End If
End Function
<Extension()>
Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean
Return _
identifierSyntax IsNot Nothing AndAlso
token = identifierSyntax.Identifier AndAlso
identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None
End Function
<Extension()>
Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean
Return _
identifierSyntax IsNot Nothing AndAlso
token = identifierSyntax.Identifier AndAlso
identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None
End Function
<Extension()>
Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean
If node Is Nothing Then
Return False
End If
Dim identifierName = TryCast(node, IdentifierNameSyntax)
If token.IsFromIdentifierNode(identifierName) Then
Return True
End If
Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax)
If token.IsFromIdentifierNode(modifiedIdentifierName) Then
Return True
End If
Return False
End Function
<Extension()>
Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean
Dim ancestor = token.GetAncestor(Of TParent)()
If ancestor Is Nothing Then
Return False
End If
Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor))
End Function
Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind,
firstLine As String,
glyph As Glyph,
intrinsicOperator As AbstractIntrinsicOperatorDocumentation,
Optional semanticModel As SemanticModel = Nothing,
Optional position As Integer = -1) As RecommendedKeyword
Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph,
Function(c)
Dim stringBuilder As New StringBuilder
stringBuilder.AppendLine(firstLine)
stringBuilder.AppendLine(intrinsicOperator.DocumentationText)
Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart))
For Each part In parts
stringBuilder.Append(part.ToString())
Next
End Sub
appendParts(intrinsicOperator.PrefixParts)
For i = 0 To intrinsicOperator.ParameterCount - 1
If i <> 0 Then
stringBuilder.Append(", ")
End If
appendParts(intrinsicOperator.GetParameterDisplayParts(i))
Next
appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c))
Return stringBuilder.ToString().ToSymbolDisplayParts()
End Function,
isIntrinsic:=True)
End Function
End Module
End Namespace
|
physhi/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/RecommendationHelpers.vb
|
Visual Basic
|
apache-2.0
| 8,955
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Test.Utilities
Imports System.Collections.Immutable
Imports System.IO
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class ChecksumTests
Inherits BasicTestBase
Private Shared Function CreateCompilationWithChecksums(source As XCData, filePath As String, baseDirectory As String) As VisualBasicCompilation
Dim tree As SyntaxTree
Using stream = New MemoryStream
Using writer = New StreamWriter(stream)
writer.Write(source.Value)
writer.Flush()
stream.Position = 0
Dim text = EncodedStringText.Create(stream, defaultEncoding:=Nothing)
tree = VisualBasicSyntaxTree.ParseText(text, path:=filePath)
End Using
End Using
Dim resolver As New SourceFileResolver(ImmutableArray(Of String).Empty, baseDirectory)
Return VisualBasicCompilation.Create(GetUniqueName(), {tree}, {MscorlibRef}, TestOptions.DebugDll.WithSourceReferenceResolver(resolver))
End Function
<Fact>
Public Sub CheckSumDirectiveClashesSameTree()
Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C
Friend Sub Foo()
End Sub
End Class
#ExternalChecksum("bogus.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' same
#ExternalChecksum("bogus.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' different case in Hex numerics, but otherwise same
#ExternalChecksum("bogus.vb", "{406ea660-64cf-4C82-B6F0-42D48172A799}", "AB007f1d23d9")
' different case in path, but is a clash since VB compares paths in a case insensitive way
#ExternalChecksum("bogUs.vb", "{406EA660-64CF-4C82-B6F0-42D48172A788}", "ab007f1d23d9")
' whitespace in path, so not a clash
#ExternalChecksum("bogUs.cs ", "{406EA660-64CF-4C82-B6F0-42D48172A788}", "ab007f1d23d9")
#ExternalChecksum("bogus1.cs", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' and now a clash in Guid
#ExternalChecksum("bogus1.cs", "{406EA660-64CF-4C82-B6F0-42D48172A798}", "ab007f1d23d9")
' and now a clash in CheckSum
#ExternalChecksum("bogus1.cs", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d8")
]]>
</file>
</compilation>, options:=TestOptions.DebugDll)
CompileAndVerify(other).VerifyDiagnostics(
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogUs.vb"", ""{406EA660-64CF-4C82-B6F0-42D48172A788}"", ""ab007f1d23d9"")").WithArguments("bogUs.vb"),
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogus1.cs"", ""{406EA660-64CF-4C82-B6F0-42D48172A798}"", ""ab007f1d23d9"")").WithArguments("bogus1.cs"),
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogus1.cs"", ""{406EA660-64CF-4C82-B6F0-42D48172A799}"", ""ab007f1d23d8"")").WithArguments("bogus1.cs")
)
End Sub
<Fact>
Public Sub CheckSumDirectiveClashesDifferentLength()
Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C
Friend Sub Foo()
End Sub
End Class
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23")
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "")
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' odd length, parse warning, ignored by emit
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d")
' bad Guid, parse warning, ignored by emit
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79}", "ab007f1d23d9")
]]>
</file>
</compilation>, options:=TestOptions.DebugDll)
CompileAndVerify(other).VerifyDiagnostics(
Diagnostic(ERRID.WRN_BadChecksumValExtChecksum, """ab007f1d23d"""),
Diagnostic(ERRID.WRN_BadGUIDFormatExtChecksum, """{406EA660-64CF-4C82-B6F0-42D48172A79}"""),
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogus1.vb"", ""{406EA660-64CF-4C82-B6F0-42D48172A799}"", ""ab007f1d23"")").WithArguments("bogus1.vb"),
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogus1.vb"", ""{406EA660-64CF-4C82-B6F0-42D48172A799}"", """")").WithArguments("bogus1.vb")
)
End Sub
<Fact>
Public Sub CheckSumDirectiveClashesDifferentTrees()
Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C
Friend Sub Foo()
End Sub
End Class
' same
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
]]>
</file>
<file name="a.vb"><![CDATA[
Public Class D
Friend Sub Foo()
End Sub
End Class
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' same
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23d9")
' different
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "ab007f1d23")
]]>
</file>
</compilation>, options:=TestOptions.DebugDll)
CompileAndVerify(other).VerifyDiagnostics(
Diagnostic(ERRID.WRN_MultipleDeclFileExtChecksum, "#ExternalChecksum(""bogus1.vb"", ""{406EA660-64CF-4C82-B6F0-42D48172A799}"", ""ab007f1d23"")").WithArguments("bogus1.vb")
)
End Sub
<Fact>
Public Sub CheckSumDirectiveFullWidth()
Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C
Friend Sub Foo()
End Sub
End Class
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23dd")
' fullwidth digit in checksum - Ok and matches
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23dd")
' fullwidth in guid - invalid guid format and ignored (same behavior as in Dev12)
#ExternalChecksum("bogus1.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23dd")
]]>
</file>
</compilation>, OutputKind.DynamicallyLinkedLibrary)
CompileAndVerify(other).VerifyDiagnostics(
Diagnostic(ERRID.WRN_BadGUIDFormatExtChecksum, """{406EA660-64CF-4C82-B6F0-42D48172A79A}""")
)
End Sub
<WorkItem(729235, "DevDiv")>
<Fact>
Public Sub NormalizedPath_Tree()
Dim source = <![CDATA[
Class C
Sub M
End Sub
End Class
]]>
Dim comp = CreateCompilationWithChecksums(source, "b.vb", "b:\base")
comp.VerifyDiagnostics()
' Only actually care about value of name attribute in file element.
comp.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="b:\base\b.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="90, B2, 29, 4D, 5, C7, A7, 47, 73, 0, EF, F4, 75, 92, E5, 84, E4, 4A, BB, E4, "/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="10" document="1"/>
<entry offset="0x1" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2">
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(729235, "DevDiv")>
<Fact>
Public Sub NormalizedPath_ExternalSource()
Dim source = <![CDATA[
Class C
Sub M
M()
#ExternalSource("line.vb", 1)
M()
#End ExternalSource
#ExternalSource("./line.vb", 2)
M()
#End ExternalSource
#ExternalSource(".\line.vb", 3)
M()
#End ExternalSource
#ExternalSource("q\..\line.vb", 4)
M()
#End ExternalSource
#ExternalSource("q:\absolute\line.vb", 5)
M()
#End ExternalSource
End Sub
End Class
]]>
Dim comp = CreateCompilationWithChecksums(source, "b.vb", "b:\base")
' Care about the fact that there's a single file element for "line.vb" and it has an absolute path.
' Care about the fact that the path that was already absolute wasn't affected by the base directory.
comp.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="b:\base\b.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="F9, 90, 0, 9D, 9E, 45, 97, F2, 3D, 67, 1C, D8, 47, A8, 9B, DA, 4A, 91, AA, 7F, "/>
<file id="2" name="b:\base\line.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
<file id="3" name="q:\absolute\line.vb" 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" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x8" startLine="1" startColumn="9" endLine="1" endColumn="12" document="2"/>
<entry offset="0xf" startLine="2" startColumn="9" endLine="2" endColumn="12" document="2"/>
<entry offset="0x16" startLine="3" startColumn="9" endLine="3" endColumn="12" document="2"/>
<entry offset="0x1d" startLine="4" startColumn="9" endLine="4" endColumn="12" document="2"/>
<entry offset="0x24" startLine="5" startColumn="9" endLine="5" endColumn="12" document="3"/>
<entry offset="0x2b" hidden="true" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2c">
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(729235, "DevDiv")>
<Fact>
Public Sub NormalizedPath_ExternalChecksum()
Dim source = <![CDATA[
Class C
#ExternalChecksum("a.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23da")
#ExternalChecksum("./b.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23db")
#ExternalChecksum(".\c.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23dc")
#ExternalChecksum("q\..\d.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23dd")
#ExternalChecksum("b:\base\e.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23de")
Sub M
M()
#ExternalSource("a.vb", 1)
M()
#End ExternalSource
#ExternalSource("b.vb", 2)
M()
#End ExternalSource
#ExternalSource("c.vb", 3)
M()
#End ExternalSource
#ExternalSource("d.vb", 4)
M()
#End ExternalSource
#ExternalSource("e.vb", 5)
M()
#End ExternalSource
End Sub
End Class
]]>
Dim comp = CreateCompilationWithChecksums(source, "file.vb", "b:\base")
' Care about the fact that all pragmas are referenced, even though the paths differ before normalization.
comp.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="b:\base\file.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="C2, 46, C6, 34, F6, 20, D3, FE, 28, B9, D8, 62, F, A9, FB, 2F, 89, E7, 48, 23, "/>
<file id="2" name="b:\base\a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DA, "/>
<file id="3" name="b:\base\b.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DB, "/>
<file id="4" name="b:\base\c.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DC, "/>
<file id="5" name="b:\base\d.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DD, "/>
<file id="6" name="b:\base\e.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DE, "/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x8" startLine="1" startColumn="9" endLine="1" endColumn="12" document="2"/>
<entry offset="0xf" startLine="2" startColumn="9" endLine="2" endColumn="12" document="3"/>
<entry offset="0x16" startLine="3" startColumn="9" endLine="3" endColumn="12" document="4"/>
<entry offset="0x1d" startLine="4" startColumn="9" endLine="4" endColumn="12" document="5"/>
<entry offset="0x24" startLine="5" startColumn="9" endLine="5" endColumn="12" document="6"/>
<entry offset="0x2b" hidden="true" document="6"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2c">
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(729235, "DevDiv")>
<Fact>
Public Sub NormalizedPath_NoBaseDirectory()
Dim source = <![CDATA[
Class C
#ExternalChecksum("a.vb", "{406EA660-64CF-4C82-B6F0-42D48172A79A}", "Ab007f1d23da")
Sub M
M()
#ExternalSource("a.vb", 1)
M()
#End ExternalSource
#ExternalSource("./a.vb", 2)
M()
#End ExternalSource
#ExternalSource("b.vb", 3)
M()
#End ExternalSource
End Sub
End Class
]]>
Dim comp = CreateCompilationWithChecksums(source, "file.vb", Nothing)
' Verify that nothing blew up.
comp.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="file.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="23, C1, 6B, 94, B0, D4, 6, 26, C8, D2, 82, 21, 63, 7, 53, 11, 4D, 5A, 2, BC, "/>
<file id="2" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a79a" checkSum="AB, 0, 7F, 1D, 23, DA, "/>
<file id="3" name="./a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
<file id="4" name="b.vb" 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" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x8" startLine="1" startColumn="9" endLine="1" endColumn="12" document="2"/>
<entry offset="0xf" startLine="2" startColumn="9" endLine="2" endColumn="12" document="3"/>
<entry offset="0x16" startLine="3" startColumn="9" endLine="3" endColumn="12" document="4"/>
<entry offset="0x1d" hidden="true" document="4"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x1e">
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/ChecksumTests.vb
|
Visual Basic
|
apache-2.0
| 17,632
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class LecturerListUI
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Label5 = New System.Windows.Forms.Label
Me.TextBoxPhone = New System.Windows.Forms.TextBox
Me.ListLect = New System.Windows.Forms.ListBox
Me.ButtonDelete = New System.Windows.Forms.Button
Me.ButtonApply = New System.Windows.Forms.Button
Me.Label3 = New System.Windows.Forms.Label
Me.TextBoxID = New System.Windows.Forms.TextBox
Me.Label2 = New System.Windows.Forms.Label
Me.TextBoxEmail = New System.Windows.Forms.TextBox
Me.TextBoxSal = New System.Windows.Forms.TextBox
Me.Label4 = New System.Windows.Forms.Label
Me.Label1 = New System.Windows.Forms.Label
Me.TextBoxLName = New System.Windows.Forms.TextBox
Me.PictureBox5 = New System.Windows.Forms.PictureBox
Me.Label6 = New System.Windows.Forms.Label
CType(Me.PictureBox5, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.BackColor = System.Drawing.Color.Transparent
Me.Label5.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label5.Location = New System.Drawing.Point(172, 213)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(77, 13)
Me.Label5.TabIndex = 36
Me.Label5.Text = "Salary/Course:"
'
'TextBoxPhone
'
Me.TextBoxPhone.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.TextBoxPhone.Enabled = False
Me.TextBoxPhone.Location = New System.Drawing.Point(285, 180)
Me.TextBoxPhone.Name = "TextBoxPhone"
Me.TextBoxPhone.Size = New System.Drawing.Size(100, 20)
Me.TextBoxPhone.TabIndex = 33
'
'ListLect
'
Me.ListLect.BackColor = System.Drawing.Color.FromArgb(CType(CType(254, Byte), Integer), CType(CType(250, Byte), Integer), CType(CType(254, Byte), Integer))
Me.ListLect.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.ListLect.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.ListLect.FormattingEnabled = True
Me.ListLect.Location = New System.Drawing.Point(25, 73)
Me.ListLect.Margin = New System.Windows.Forms.Padding(0)
Me.ListLect.Name = "ListLect"
Me.ListLect.Size = New System.Drawing.Size(117, 247)
Me.ListLect.TabIndex = 42
'
'ButtonDelete
'
Me.ButtonDelete.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.ButtonDelete.BackColor = System.Drawing.Color.White
Me.ButtonDelete.Enabled = False
Me.ButtonDelete.Location = New System.Drawing.Point(247, 340)
Me.ButtonDelete.Name = "ButtonDelete"
Me.ButtonDelete.Size = New System.Drawing.Size(100, 23)
Me.ButtonDelete.TabIndex = 39
Me.ButtonDelete.Text = "Delete Account"
Me.ButtonDelete.UseVisualStyleBackColor = False
'
'ButtonApply
'
Me.ButtonApply.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.ButtonApply.BackColor = System.Drawing.Color.White
Me.ButtonApply.Enabled = False
Me.ButtonApply.Location = New System.Drawing.Point(353, 340)
Me.ButtonApply.Name = "ButtonApply"
Me.ButtonApply.Size = New System.Drawing.Size(75, 23)
Me.ButtonApply.TabIndex = 38
Me.ButtonApply.Text = "Apply"
Me.ButtonApply.UseVisualStyleBackColor = False
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.BackColor = System.Drawing.Color.Transparent
Me.Label3.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label3.Location = New System.Drawing.Point(172, 88)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(63, 13)
Me.Label3.TabIndex = 41
Me.Label3.Text = "Lecturer ID:"
'
'TextBoxID
'
Me.TextBoxID.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.TextBoxID.Enabled = False
Me.TextBoxID.Location = New System.Drawing.Point(285, 85)
Me.TextBoxID.Name = "TextBoxID"
Me.TextBoxID.ReadOnly = True
Me.TextBoxID.Size = New System.Drawing.Size(100, 20)
Me.TextBoxID.TabIndex = 40
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.BackColor = System.Drawing.Color.Transparent
Me.Label2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label2.Location = New System.Drawing.Point(172, 150)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(35, 13)
Me.Label2.TabIndex = 32
Me.Label2.Text = "Email:"
'
'TextBoxEmail
'
Me.TextBoxEmail.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.TextBoxEmail.Enabled = False
Me.TextBoxEmail.Location = New System.Drawing.Point(285, 147)
Me.TextBoxEmail.Name = "TextBoxEmail"
Me.TextBoxEmail.Size = New System.Drawing.Size(148, 20)
Me.TextBoxEmail.TabIndex = 31
'
'TextBoxSal
'
Me.TextBoxSal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.TextBoxSal.Enabled = False
Me.TextBoxSal.Location = New System.Drawing.Point(285, 210)
Me.TextBoxSal.Name = "TextBoxSal"
Me.TextBoxSal.Size = New System.Drawing.Size(100, 20)
Me.TextBoxSal.TabIndex = 35
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.BackColor = System.Drawing.Color.Transparent
Me.Label4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label4.Location = New System.Drawing.Point(172, 183)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(41, 13)
Me.Label4.TabIndex = 34
Me.Label4.Text = "Phone:"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.BackColor = System.Drawing.Color.Transparent
Me.Label1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label1.Location = New System.Drawing.Point(172, 119)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(38, 13)
Me.Label1.TabIndex = 30
Me.Label1.Text = "Name:"
'
'TextBoxLName
'
Me.TextBoxLName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.TextBoxLName.Enabled = False
Me.TextBoxLName.Location = New System.Drawing.Point(285, 116)
Me.TextBoxLName.Name = "TextBoxLName"
Me.TextBoxLName.ReadOnly = True
Me.TextBoxLName.Size = New System.Drawing.Size(100, 20)
Me.TextBoxLName.TabIndex = 29
'
'PictureBox5
'
Me.PictureBox5.BackColor = System.Drawing.Color.Transparent
Me.PictureBox5.Image = Global.Summer_Course_System.My.Resources.Resources.ceo
Me.PictureBox5.Location = New System.Drawing.Point(25, 12)
Me.PictureBox5.Name = "PictureBox5"
Me.PictureBox5.Size = New System.Drawing.Size(32, 32)
Me.PictureBox5.TabIndex = 43
Me.PictureBox5.TabStop = False
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.BackColor = System.Drawing.Color.Transparent
Me.Label6.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label6.Location = New System.Drawing.Point(63, 16)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(124, 24)
Me.Label6.TabIndex = 44
Me.Label6.Text = "Lecturer List"
'
'LecturerListUI
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(254, Byte), Integer), CType(CType(250, Byte), Integer), CType(CType(254, Byte), Integer))
Me.BackgroundImage = Global.Summer_Course_System.My.Resources.Resources.header
Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.ClientSize = New System.Drawing.Size(453, 386)
Me.Controls.Add(Me.PictureBox5)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.ButtonDelete)
Me.Controls.Add(Me.ListLect)
Me.Controls.Add(Me.ButtonApply)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.TextBoxID)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.TextBoxLName)
Me.Controls.Add(Me.TextBoxPhone)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.TextBoxEmail)
Me.Controls.Add(Me.TextBoxSal)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "LecturerListUI"
Me.ShowIcon = False
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.Text = "Lecturer List"
CType(Me.PictureBox5, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label5 As System.Windows.Forms.Label
Friend WithEvents TextBoxPhone As System.Windows.Forms.TextBox
Friend WithEvents ListLect As System.Windows.Forms.ListBox
Friend WithEvents ButtonDelete As System.Windows.Forms.Button
Friend WithEvents ButtonApply As System.Windows.Forms.Button
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents TextBoxID As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents TextBoxEmail As System.Windows.Forms.TextBox
Friend WithEvents TextBoxSal As System.Windows.Forms.TextBox
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents TextBoxLName As System.Windows.Forms.TextBox
Friend WithEvents PictureBox5 As System.Windows.Forms.PictureBox
Friend WithEvents Label6 As System.Windows.Forms.Label
End Class
|
louislam/summer-course-system
|
Summer Course System/UI/LecturerListUI.Designer.vb
|
Visual Basic
|
mit
| 10,572
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing
Dim sheet As SolidEdgeDraft.Sheet = Nothing
Dim centerMarks As SolidEdgeFrameworkSupport.CenterMarks = Nothing
Dim centerMark As SolidEdgeFrameworkSupport.CenterMark = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument)
sheet = draftDocument.ActiveSheet
centerMarks = CType(sheet.CenterMarks, SolidEdgeFrameworkSupport.CenterMarks)
centerMark = centerMarks.Add(0.25, 0.25, 0)
Dim Name = "MyAttributeSet"
Dim attributeSetPresent = centerMark.IsAttributeSetPresent(Name)
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.CenterMark.IsAttributeSetPresent.vb
|
Visual Basic
|
mit
| 1,707
|
Imports System.Drawing
Public Class SingleIonLayer
Public Property IonMz As Double
Public Property MSILayer As PixelData()
Public Property DimensionSize As Size
Public Function GetIntensity() As Double()
Return MSILayer.Select(Function(p) p.intensity).ToArray
End Function
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/visualize/MsImaging/SingleIonLayer.vb
|
Visual Basic
|
mit
| 318
|
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 materialTable As SolidEdgeFramework.MatTable = 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 = CType(application.ActiveDocument, SolidEdgePart.PartDocument)
materialTable = application.GetMaterialTable()
materialTable.SetActiveDocument(partDocument)
Dim materialName = "MyMaterial"
Dim libraryName = "Materials"
Dim materialsPath = "Others"
Dim faceStyle = "Copper"
Dim fillStyle = "ANSI33(Brass)"
' Define exactly 9 material properties in this specific order (pay attention to the units!!):
' 1) Density [kg/m3]
' 2) Coef. of Thermal Exp. [1/ºC]
' 3) Thermal Conductivity [W/mºC]
' 4) Specific Heat [J/kgºC]
' 5) Modulus of Elasticity [Pa]
' 6) Poisson's Ratio[unitless]
' 7) Yield Stress [Pa]
' 8) Ultimate Stress [Pa]
' 9) Elongation % [unitless]
Dim propList = New Object() { 7888.0, 0.0, 51.0, 500.0, 69985996255.0, 711.0, 250000000.0, 745000000.0, 0.0 }
materialTable.AddMaterialToLibrary(materialName, libraryName, materialsPath, propList.Length, propList, faceStyle, fillStyle)
materialTable.DeleteMaterialFromLibrary(materialName, libraryName)
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFramework.MatTable.AddMaterialToLibrary.vb
|
Visual Basic
|
mit
| 2,267
|
Imports Net.Surviveplus.Localization
Public Class Replace
''' <summary>
''' Initializes a new instance of the class.
''' </summary>
''' <remarks></remarks>
Public Sub New()
InitializeComponent()
WpfLocalization.ApplyResources(Me, My.Resources.ResourceManager)
Me.findBox.SelectAll()
Me.findBox.Focus()
End Sub
Private Sub ReplaceAllButton_Click(sender As Object, e As RoutedEventArgs)
RaiseEvent RepaceButtonClick(Me, New ReplaceToolControlEventArgs With {.FindText = Me.findBox.Text, .ReplaceText = Me.replaceBox.Text})
End Sub
Public Event RepaceButtonClick As EventHandler(Of ReplaceToolControlEventArgs)
End Class
Public Class ReplaceToolControlEventArgs
Inherits EventArgs
Public Property FindText As String
Public Property ReplaceText As String
End Class
|
surviveplus/EditorPlus
|
office2013/EditorPlus.UI/EditorPlus.UI/Replace.xaml.vb
|
Visual Basic
|
mit
| 863
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.Drawing
Imports Bytescout.Watermarking
Imports Bytescout.Watermarking.Presets
Module Module1
Sub Main()
' Create Watermarker instance
Dim watermarker As New Watermarker()
Dim inputFilePath As String
Dim outputFilePath As String
' Initialize library
watermarker.InitLibrary("demo", "demo")
' Set input file name
inputFilePath = "my_sample_image.jpg"
' Set output file title
outputFilePath = "my_sample_output.png"
' Add image to apply watermarks to
watermarker.AddInputFile(inputFilePath, outputFilePath)
' Create new watermark
Dim preset As New TextAnnotation()
' Set radius of the corners of the rectangle
preset.Radius = 30
' Set text
preset.Text = "Date and Time: {{LOCAL_DATE_LONG}} {{LOCAL_TIME}}" + vbCrLf
preset.Text += "Path: {{DIRECTORY}}" + vbCrLf
preset.Text += "Filename: {{FILENAME}}" + vbCrLf
preset.Text += "Manufacturer: {{EXIF_EQUIPMENT_MANUFACTURER}}" + vbCrLf
preset.Text += "Model: {{EXIF_EQUIPMENT_MODEL}}" + vbCrLf
preset.Text += "Software: {{EXIF_SOFTWARE_USED}}" + vbCrLf
preset.Text += "Date/Time: {{EXIF_ORIGINAL_DATE}}" + vbCrLf
preset.Text += "Exposure Time: {{EXIF_EXPOSURE_TIME}} sec" + vbCrLf
preset.Text += "Exposure Program: {{EXIF_EXPOSURE_PROGRAM}}" + vbCrLf
preset.Text += "Exposure Bias: {{EXIF_EXPOSURE_BIAS}} EV" + vbCrLf
preset.Text += "F Number: F {{EXIF_F_NUMBER}}" + vbCrLf
preset.Text += "ISO Speed Rating: ISO {{EXIF_ISO_SPEED}}" + vbCrLf
preset.Text += "Flash: {{EXIF_FLASH}}" + vbCrLf
preset.Text += "Focal Length: {{EXIF_FOCAL_LENGTH}} mm" + vbCrLf
preset.Text += "Metering Mode: {{EXIF_METERING_MODE}}" + vbCrLf
' Set watermark font
preset.Font = New WatermarkFont("Tahoma", FontStyle.Regular, FontSizeType.Points, 7)
' Add watermark to watermarker
watermarker.AddWatermark(preset)
' Set output directory
watermarker.OutputOptions.OutputDirectory = "."
' Set output format
watermarker.OutputOptions.ImageFormat = OutputFormats.PNG
' Apply watermarks
watermarker.Execute()
' open generated image file in default image viewer installed in Windows
Process.Start(outputFilePath)
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Watermarking SDK/VB.NET/Use Macros for Watermarks/Module1.vb
|
Visual Basic
|
apache-2.0
| 3,449
|
' 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.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
<CompilerTrait(CompilerFeature.Tuples)>
Public Class CodeGenTuples
Inherits BasicTestBase
ReadOnly s_valueTupleRefs As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef}
ReadOnly s_valueTupleRefsAndDefault As MetadataReference() = New MetadataReference() {ValueTupleRef,
SystemRuntimeFacadeRef,
MscorlibRef,
SystemRef,
SystemCoreRef,
MsvbRef}
ReadOnly s_trivial2uple As String = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}""
End Function
End Structure
End Namespace
namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )>
public class TupleElementNamesAttribute : Inherits Attribute
public Sub New(transformNames As String())
End Sub
End Class
End Namespace
"
ReadOnly s_tupleattributes As String = "
namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )>
public class TupleElementNamesAttribute : Inherits Attribute
public Sub New(transformNames As String())
End Sub
End Class
End Namespace
"
ReadOnly s_trivial3uple As String = "
Namespace System
Public Structure ValueTuple(Of T1, T2, T3)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Dim Item3 As T3
Public Sub New(item1 As T1, item2 As T2, item3 As T3)
me.Item1 = item1
me.Item2 = item2
me.Item3 = item3
End Sub
End Structure
End Namespace
"
ReadOnly s_trivialRemainingTuples As String = "
Namespace System
Public Structure ValueTuple(Of T1, T2, T3, T4)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4)
End Sub
End Structure
Public Structure ValueTuple(Of T1, T2, T3, T4, T5)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5)
End Sub
End Structure
Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6)
End Sub
End Structure
Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7)
End Sub
End Structure
Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest)
End Sub
End Structure
End Namespace
"
<Fact>
Public Sub TupleNamesInArrayInAttribute()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
<My(New (String, bob As String)() { })>
Public Class MyAttribute
Inherits System.Attribute
Public Sub New(x As (alice As String, String)())
End Sub
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30045: Attribute constructor has a parameter of type '(alice As String, String)()', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.
<My(New (String, bob As String)() { })>
~~
]]></errors>)
End Sub
<Fact>
Public Sub TupleTypeBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
console.writeline(t)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Overrides Function ToString() As String
Return "hello"
End Function
End Structure
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloc.0
IL_0001: box "System.ValueTuple(Of Integer, Integer)"
IL_0006: call "Sub System.Console.WriteLine(Object)"
IL_000b: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleTypeBindingTypeChar()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
option strict on
Imports System
Module C
Sub Main()
Dim t as (A%, B$) = Nothing
console.writeline(t.GetType())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.ValueTuple`2[System.Int32,System.String]
]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
.locals init (System.ValueTuple(Of Integer, String) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: initobj "System.ValueTuple(Of Integer, String)"
IL_0008: ldloc.0
IL_0009: box "System.ValueTuple(Of Integer, String)"
IL_000e: call "Function Object.GetType() As System.Type"
IL_0013: call "Sub System.Console.WriteLine(Object)"
IL_0018: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleTypeBindingTypeChar1()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
option strict off
Imports System
Module C
Sub Main()
Dim t as (A%, B$) = Nothing
console.writeline(t.GetType())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.ValueTuple`2[System.Int32,System.String]
]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
.locals init (System.ValueTuple(Of Integer, String) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: initobj "System.ValueTuple(Of Integer, String)"
IL_0008: ldloc.0
IL_0009: box "System.ValueTuple(Of Integer, String)"
IL_000e: call "Function Object.GetType() As System.Type"
IL_0013: call "Sub System.Console.WriteLine(Object)"
IL_0018: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleTypeBindingTypeCharErr()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim t as (A% As String, B$ As String, C As String$) = nothing
console.writeline(t.A.Length) 'A should not take the type from % in this case
Dim t1 as (String$, String%) = nothing
console.writeline(t1.GetType())
Dim B = 1
Dim t2 = (A% := "qq", B$)
console.writeline(t2.A.Length) 'A should not take the type from % in this case
Dim t3 As (V1(), V2%()) = Nothing
console.writeline(t3.Item1.Length)
End Sub
Async Sub T()
Dim t4 as (Integer% As String, Await As String, Function$) = nothing
console.writeline(t4.Integer.Length)
console.writeline(t4.Await.Length)
console.writeline(t4.Function.Length)
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
console.writeline(t4.Function.Length)
End Sub
class V2
end class
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim t as (A% As String, B$ As String, C As String$) = nothing
~~
BC30302: Type character '$' cannot be used in a declaration with an explicit type.
Dim t as (A% As String, B$ As String, C As String$) = nothing
~~
BC30468: Type declaration characters are not valid in this context.
Dim t as (A% As String, B$ As String, C As String$) = nothing
~~~~~~~
BC37262: Tuple element names must be unique.
Dim t1 as (String$, String%) = nothing
~~~~~~~
BC37270: Type characters cannot be used in tuple literals.
Dim t2 = (A% := "qq", B$)
~~
BC30277: Type character '$' does not match declared data type 'Integer'.
Dim t2 = (A% := "qq", B$)
~~
BC30002: Type 'V1' is not defined.
Dim t3 As (V1(), V2%()) = Nothing
~~
BC32017: Comma, ')', or a valid expression continuation expected.
Dim t3 As (V1(), V2%()) = Nothing
~
BC42356: This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.
Async Sub T()
~
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim t4 as (Integer% As String, Await As String, Function$) = nothing
~~~~~~~~
BC30183: Keyword is not valid as an identifier.
Dim t4 as (Integer% As String, Await As String, Function$) = nothing
~~~~~
BC30180: Keyword does not name a type.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~
BC30180: Keyword does not name a type.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~
BC30002: Type 'Junk2' is not defined.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~~~~~
BC32017: Comma, ')', or a valid expression continuation expected.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~~~~~~~~
BC30002: Type 'Junk4' is not defined.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~~~~~
BC32017: Comma, ')', or a valid expression continuation expected.
Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing
~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleTypeBindingNoTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
console.writeline(t)
console.writeline(t.Item1)
Dim t1 as (A As Integer, B As Integer)
console.writeline(t1)
console.writeline(t1.Item1)
console.writeline(t1.A)
End Sub
End Module
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim t as (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim t1 as (A As Integer, B As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
Dim t1 as (A As Integer, B As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleDefaultType001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t = (Nothing, Nothing)
console.writeline(t)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, )
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldnull
IL_0001: ldnull
IL_0002: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)"
IL_0007: box "System.ValueTuple(Of Object, Object)"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType001err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim t = (Nothing, Nothing)
console.writeline(t)
End Sub
End Module
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim t = (Nothing, Nothing)
~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub TupleDefaultType002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t1 = ({Nothing}, {Nothing})
console.writeline(t1.GetType())
Dim t2 = {(Nothing, Nothing)}
console.writeline(t2.GetType())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.ValueTuple`2[System.Object[],System.Object[]]
System.ValueTuple`2[System.Object,System.Object][]
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t3 = Function(){(Nothing, Nothing)}
console.writeline(t3.GetType())
Dim t4 = {Function()(Nothing, Nothing)}
console.writeline(t4.GetType())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object][]]
VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object]][]
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Test(({Nothing}, {{Nothing}}))
Test((Function(x as integer)x, Function(x as Long)x))
End Sub
function Test(of T, U)(x as (T, U)) as (U, T)
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine()
return (x.Item2, x.Item1)
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Object[]
System.Object[,]
VB$AnonymousDelegate_0`2[System.Int32,System.Int32]
VB$AnonymousDelegate_0`2[System.Int64,System.Int64]
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Test((Function(x as integer)Function()x, Function(x as Long){({Nothing}, {Nothing})}))
End Sub
function Test(of T, U)(x as (T, U)) as (U, T)
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine()
return (x.Item2, x.Item1)
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
VB$AnonymousDelegate_0`2[System.Int32,VB$AnonymousDelegate_1`1[System.Int32]]
VB$AnonymousDelegate_0`2[System.Int64,System.ValueTuple`2[System.Object[],System.Object[]][]]
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Test((Nothing, Nothing), "q")
Test((Nothing, "q"), Nothing)
Test1("q", (Nothing, Nothing))
Test1(Nothing, ("q", Nothing))
End Sub
function Test(of T)(x as (T, T), y as T) as T
System.Console.WriteLine(GetType(T))
return y
End Function
function Test1(of T)(x as T, y as (T, T)) as T
System.Console.WriteLine(GetType(T))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.String
System.String
System.String
System.String
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType006err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Test1((Nothing, Nothing), Nothing)
Test2(Nothing, (Nothing, Nothing))
End Sub
function Test1(of T)(x as (T, T), y as T) as T
System.Console.WriteLine(GetType(T))
return y
End Function
function Test2(of T)(x as T, y as (T, T)) as T
System.Console.WriteLine(GetType(T))
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As (T, T), y As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test1((Nothing, Nothing), Nothing)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As T, y As (T, T)) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(Nothing, (Nothing, Nothing))
~~~~~
</errors>)
End Sub
<Fact()>
Public Sub TupleDefaultType007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim valid As (A as Action, B as Action) = (AddressOf Main, AddressOf Main)
Test2(valid)
Test2((AddressOf Main, Sub() Main))
End Sub
function Test2(of T)(x as (T, T)) as (T, T)
System.Console.WriteLine(GetType(T))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Action
VB$AnonymousDelegate_0
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultType007err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x = (AddressOf Main, AddressOf Main)
Dim x1 = (Function() Main, Function() Main)
Dim x2 = (AddressOf Mai, Function() Mai)
Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main))
Test1((AddressOf Main, Sub() Main))
Test1((AddressOf Main, Function() Main))
Test2((AddressOf Main, Function() Main))
End Sub
function Test1(of T)(x as T) as T
System.Console.WriteLine(GetType(T))
return x
End Function
function Test2(of T)(x as (T, T)) as (T, T)
System.Console.WriteLine(GetType(T))
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30491: Expression does not produce a value.
Dim x = (AddressOf Main, AddressOf Main)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30491: Expression does not produce a value.
Dim x1 = (Function() Main, Function() Main)
~~~~
BC30491: Expression does not produce a value.
Dim x1 = (Function() Main, Function() Main)
~~~~
BC30451: 'Mai' is not declared. It may be inaccessible due to its protection level.
Dim x2 = (AddressOf Mai, Function() Mai)
~~~
BC30491: Expression does not produce a value.
Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test1((AddressOf Main, Sub() Main))
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test1((AddressOf Main, Function() Main))
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As (T, T)) As (T, T)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2((AddressOf Main, Function() Main))
~~~~~
</errors>)
End Sub
<Fact()>
Public Sub DataFlow()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
dim initialized as Object = Nothing
dim baseline_literal = (initialized, initialized)
dim uninitialized as Object
dim literal = (uninitialized, uninitialized)
dim uninitialized1 as Exception
dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1)
dim uninitialized2 as Exception
dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC42104: Variable 'uninitialized' is used before it has been assigned a value. A null reference exception could result at runtime.
dim literal = (uninitialized, uninitialized)
~~~~~~~~~~~~~
BC42104: Variable 'uninitialized1' is used before it has been assigned a value. A null reference exception could result at runtime.
dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1)
~~~~~~~~~~~~~~
BC42104: Variable 'uninitialized2' is used before it has been assigned a value. A null reference exception could result at runtime.
dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2)
~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
t.Item1 = 42
t.Item2 = t.Item1
console.writeline(t.Item2)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
End Structure
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
42
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0009: ldloca.s V_0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0016: ldloc.0
IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001c: call "Sub System.Console.WriteLine(Integer)"
IL_0021: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleFieldBinding01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim vt as ValueTuple(Of Integer, Integer) = M1(2,3)
console.writeline(vt.Item2)
End Sub
Function M1(x As Integer, y As Integer) As ValueTuple(Of Integer, Integer)
Return New ValueTuple(Of Integer, Integer)(x, y)
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
3
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("C.M1", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: ret
}
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: call "Function C.M1(Integer, Integer) As (Integer, Integer)"
IL_0007: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_000c: call "Sub System.Console.WriteLine(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleFieldBindingLong()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer, Integer, integer, integer, integer, integer, integer, integer, Integer, Integer, String, integer, integer, integer, integer, String, integer)
t.Item17 = "hello"
t.Item12 = t.Item17
console.writeline(t.Item12)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 67 (0x43)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)"
IL_000c: ldstr "hello"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String"
IL_0016: ldloca.s V_0
IL_0018: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_001d: ldloc.0
IL_001e: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0023: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)"
IL_0028: ldfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String"
IL_002d: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String"
IL_0032: ldloc.0
IL_0033: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0038: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String"
IL_003d: call "Sub System.Console.WriteLine(String)"
IL_0042: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleNamedFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t As (a As Integer, b As Integer)
t.a = 42
t.b = t.a
Console.WriteLine(t.b)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
End Structure
End Namespace
namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )>
public class TupleElementNamesAttribute : Inherits Attribute
public Sub New(transformNames As String())
End Sub
End Class
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
42
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0009: ldloca.s V_0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0016: ldloc.0
IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001c: call "Sub System.Console.WriteLine(Integer)"
IL_0021: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleDefaultFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim t As (Integer, Integer) = nothing
t.Item1 = 42
t.Item2 = t.Item1
Console.WriteLine(t.Item2)
Dim t1 = (A:=1, B:=123)
Console.WriteLine(t1.B)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
42
123
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: initobj "System.ValueTuple(Of Integer, Integer)"
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.s 42
IL_000c: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: ldloca.s V_0
IL_0013: ldloc.0
IL_0014: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0019: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001e: ldloc.0
IL_001f: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0024: call "Sub System.Console.WriteLine(Integer)"
IL_0029: ldc.i4.1
IL_002a: ldc.i4.s 123
IL_002c: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0031: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0036: call "Sub System.Console.WriteLine(Integer)"
IL_003b: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleNamedFieldBindingLong()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)
t.a17 = 42
t.a12 = t.a17
console.writeline(t.a12)
TestArray()
TestNullable()
End Sub
Sub TestArray()
Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)() {Nothing}
t(0).a17 = 42
t(0).a12 = t(0).a17
console.writeline(t(0).a12)
End Sub
Sub TestNullable()
Dim t as New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)?
console.writeline(t.HasValue)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
42
42
False
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 74 (0x4a)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)"
IL_000c: ldc.i4.s 42
IL_000e: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer"
IL_0013: ldloca.s V_0
IL_0015: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_001a: ldloc.0
IL_001b: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0020: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)"
IL_0025: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer"
IL_002a: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer"
IL_002f: ldloc.0
IL_0030: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0035: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer"
IL_003a: call "Sub System.Console.WriteLine(Integer)"
IL_003f: call "Sub C.TestArray()"
IL_0044: call "Sub C.TestNullable()"
IL_0049: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleNewLongErr()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as String,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)
console.writeline(t.a12.Length)
Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as String,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)
console.writeline(t1.a12.Length)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
' should not complain about missing constructor
comp.AssertTheseDiagnostics(
<errors>
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleDisallowedWithNew()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Dim t1 = New (a1 as Integer, a2 as Integer)()
Dim t2 As New (a1 as Integer, a2 as Integer)
Sub M()
Dim t1 = New (a1 as Integer, a2 as Integer)()
Dim t2 As New (a1 as Integer, a2 as Integer)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t1 = New (a1 as Integer, a2 as Integer)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t2 As New (a1 as Integer, a2 as Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t1 = New (a1 as Integer, a2 as Integer)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim t2 As New (a1 as Integer, a2 as Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub ParseNewTuple()
Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Sub Main()
Dim x = New (A, A)
Dim y = New (A, A)()
Dim z = New (x As Integer, A)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp1.AssertTheseDiagnostics(<errors>
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim x = New (A, A)
~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim y = New (A, A)()
~~~~~~
BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead.
Dim z = New (x As Integer, A)
~~~~~~~~~~~~~~~~~
</errors>)
Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer)
' this is actually ok, since it is an array
Return (New(Integer, Integer)() {(4, 5)}, 5)
End Function
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp2.AssertNoDiagnostics()
End Sub
<Fact>
Public Sub TupleLiteralBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer) = (1, 2)
console.writeline(t)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
(1, 2)
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: box "System.ValueTuple(Of Integer, Integer)"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleLiteralBindingNamed()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t = (A := 1, B := "hello")
console.writeline(t.B)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>, references:=s_valueTupleRefs)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldstr "hello"
IL_0006: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000b: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_0010: call "Sub System.Console.WriteLine(String)"
IL_0015: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleLiteralSample()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Module Module1
Sub Main()
Dim t As (Integer, Integer) = Nothing
t.Item1 = 42
t.Item2 = t.Item1
Console.WriteLine(t.Item2)
Dim t1 = (A:=1, B:=123)
Console.WriteLine(t1.B)
Dim numbers = {1, 2, 3, 4}
Dim t2 = Tally(numbers).Result
System.Console.WriteLine($"Sum: {t2.Sum}, Count: {t2.Count}")
End Sub
Public Async Function Tally(values As IEnumerable(Of Integer)) As Task(Of (Sum As Integer, Count As Integer))
Dim s = 0, c = 0
For Each n In values
s += n
c += 1
Next
'Await Task.Yield()
Return (Sum:=s, Count:=c)
End Function
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Sub New(item1 as T1, item2 as T2)
Me.Item1 = item1
Me.Item2 = item2
End Sub
End Structure
End Namespace
namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )>
public class TupleElementNamesAttribute : Inherits Attribute
public Sub New(transformNames As String())
End Sub
End Class
End Namespace
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42
123
Sum: 10, Count: 4")
End Sub
<Fact>
<WorkItem(18762, "https://github.com/dotnet/roslyn/issues/18762")>
Public Sub UnnamedTempShouldNotCrashPdbEncoding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Private Async Function DoAllWorkAsync() As Task(Of (FirstValue As String, SecondValue As String))
Return (Nothing, Nothing)
End Function
End Module
</file>
</compilation>,
references:={ValueTupleRef, SystemRuntimeFacadeRef}, useLatestFramework:=True, options:=TestOptions.DebugDll)
End Sub
<Fact>
Public Sub Overloading001()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
Sub Test(x as (a as integer, b as Integer))
End Sub
Sub Test(x as (c as integer, d as Integer))
End Sub
End module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37271: 'Public Sub Test(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (c As Integer, d As Integer))'.
Sub Test(x as (a as integer, b as Integer))
~~~~
</errors>)
End Sub
<Fact>
Public Sub Overloading002()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
Sub Test(x as (integer,Integer))
End Sub
Sub Test(x as (a as integer, b as Integer))
End Sub
End module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37271: 'Public Sub Test(x As (Integer, Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (a As Integer, b As Integer))'.
Sub Test(x as (integer,Integer))
~~~~
</errors>)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (String, String) = (Nothing, Nothing)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, )
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (System.ValueTuple(Of String, String) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldnull
IL_0004: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)"
IL_0009: ldloca.s V_0
IL_000b: constrained. "System.ValueTuple(Of String, String)"
IL_0011: callvirt "Function Object.ToString() As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(Nothing, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped001Err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing)
System.Console.WriteLine(x.ToString())
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(C As Object, D As Object, E As Object)' cannot be converted to '(A As String, B As String)'.
Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() "hi")
System.Console.WriteLine((x.Item1(), x.Item2()).ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(42, hi)
]]>)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped002a()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() Nothing)
System.Console.WriteLine((x.Item1(), x.Item2()).ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(42, )
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub SimpleTupleTargetTyped003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = CType((Nothing, 1),(String, Byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, 1)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (System.ValueTuple(Of String, Byte) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldc.i4.1
IL_0004: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_0009: ldloca.s V_0
IL_000b: constrained. "System.ValueTuple(Of String, Byte)"
IL_0011: callvirt "Function Object.ToString() As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
Dim compilation = verifier.Compilation
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single()
Assert.Equal("CType((Nothing, 1),(String, Byte))", node.ToString())
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'CType((Noth ... ing, Byte))')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.String, System.Byte)) (Syntax: '(Nothing, 1)')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = DirectCast((Nothing, 1),(String, String))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, 1)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
.locals init (System.ValueTuple(Of String, String) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldc.i4.1
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)"
IL_000e: ldloca.s V_0
IL_0010: constrained. "System.ValueTuple(Of String, String)"
IL_0016: callvirt "Function Object.ToString() As String"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
}
]]>)
End Sub
<Fact>
Public Sub SimpleTupleTargetTyped005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = CType((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub SimpleTupleTargetTyped006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = DirectCast((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
Dim compilation = verifier.Compilation
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of DirectCastExpressionSyntax)().Single()
Assert.Equal("DirectCast((Nothing, i),(String, byte))", node.ToString())
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'DirectCast( ... ing, byte))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub SimpleTupleTargetTyped007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = TryCast((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
Dim compilation = verifier.Compilation
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TryCastExpressionSyntax)().Single()
Assert.Equal("TryCast((Nothing, i),(String, byte))", node.ToString())
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'TryCast((No ... ing, byte))')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value)
Dim model = compilation.GetSemanticModel(tree)
Dim typeInfo = model.GetTypeInfo(node.Expression)
Assert.Null(typeInfo.Type)
Assert.Equal("(System.String, i As System.Byte)", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Expression).Kind)
End Sub
<Fact>
Public Sub TupleConversionWidening()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte) = (a:=100, b:=100)
Dim x as (integer, double) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Double) V_0, //x
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0010: ldloc.1
IL_0011: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0016: conv.r8
IL_0017: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: constrained. "System.ValueTuple(Of Integer, Double)"
IL_0025: callvirt "Function Object.ToString() As String"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(a:=100, b:=100)", node.ToString())
Assert.Equal("(a As Integer, b As Integer)", model.GetTypeInfo(node).Type.ToDisplayString())
Assert.Equal("(x As System.Byte, y As System.Byte)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
End Sub
<Fact>
Public Sub TupleConversionNarrowing()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (Integer, String) = (100, 100)
Dim x as (Byte, Byte) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //x
System.ValueTuple(Of Integer, String) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer"
IL_0015: conv.ovf.u1
IL_0016: ldloc.1
IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte"
IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0026: stloc.0
IL_0027: ldloca.s V_0
IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)"
IL_002f: callvirt "Function Object.ToString() As String"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(100, 100)", node.ToString())
Assert.Equal("(Integer, Integer)", model.GetTypeInfo(node).Type.ToDisplayString())
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind)
End Sub
<Fact>
Public Sub TupleConversionNarrowingUnchecked()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (Integer, String) = (100, 100)
Dim x as (Byte, Byte) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //x
System.ValueTuple(Of Integer, String) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer"
IL_0015: conv.u1
IL_0016: ldloc.1
IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte"
IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0026: stloc.0
IL_0027: ldloca.s V_0
IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)"
IL_002f: callvirt "Function Object.ToString() As String"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionObject()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (object, object) = (1, (2,3))
Dim x as (integer, (integer, integer)) = ctype(i, (integer, (integer, integer)))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(1, (2, 3))
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 86 (0x56)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, (Integer, Integer)) V_0, //x
System.ValueTuple(Of Object, Object) V_1,
System.ValueTuple(Of Integer, Integer) V_2)
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: ldc.i4.2
IL_0007: ldc.i4.3
IL_0008: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_000d: box "System.ValueTuple(Of Integer, Integer)"
IL_0012: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)"
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldfld "System.ValueTuple(Of Object, Object).Item1 As Object"
IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer"
IL_0023: ldloc.1
IL_0024: ldfld "System.ValueTuple(Of Object, Object).Item2 As Object"
IL_0029: dup
IL_002a: brtrue.s IL_0038
IL_002c: pop
IL_002d: ldloca.s V_2
IL_002f: initobj "System.ValueTuple(Of Integer, Integer)"
IL_0035: ldloc.2
IL_0036: br.s IL_003d
IL_0038: unbox.any "System.ValueTuple(Of Integer, Integer)"
IL_003d: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))"
IL_0042: stloc.0
IL_0043: ldloca.s V_0
IL_0045: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))"
IL_004b: callvirt "Function Object.ToString() As String"
IL_0050: call "Sub System.Console.WriteLine(String)"
IL_0055: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionOverloadResolution()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim b as (byte, byte) = (100, 100)
Test(b)
Dim i as (integer, integer) = b
Test(i)
Dim l as (Long, integer) = b
Test(l)
End Sub
Sub Test(x as (integer, integer))
System.Console.Writeline("integer")
End SUb
Sub Test(x as (Long, Long))
System.Console.Writeline("long")
End SUb
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
integer
integer
long ]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 101 (0x65)
.maxstack 3
.locals init (System.ValueTuple(Of Byte, Byte) V_0,
System.ValueTuple(Of Long, Integer) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0009: dup
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0011: ldloc.0
IL_0012: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0017: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_001c: call "Sub C.Test((Integer, Integer))"
IL_0021: dup
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0029: ldloc.0
IL_002a: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_002f: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0034: call "Sub C.Test((Integer, Integer))"
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0040: conv.u8
IL_0041: ldloc.0
IL_0042: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0047: newobj "Sub System.ValueTuple(Of Long, Integer)..ctor(Long, Integer)"
IL_004c: stloc.1
IL_004d: ldloc.1
IL_004e: ldfld "System.ValueTuple(Of Long, Integer).Item1 As Long"
IL_0053: ldloc.1
IL_0054: ldfld "System.ValueTuple(Of Long, Integer).Item2 As Integer"
IL_0059: conv.i8
IL_005a: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_005f: call "Sub C.Test((Long, Long))"
IL_0064: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionNullable001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte)? = (a:=100, b:=100)
Dim x as (integer, double) = CType(i, (integer, double))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 62 (0x3e)
.maxstack 3
.locals init ((x As Byte, y As Byte)? V_0, //i
System.ValueTuple(Of Integer, Double) V_1, //x
System.ValueTuple(Of Byte, Byte) V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (x As Byte, y As Byte)?.get_Value() As (x As Byte, y As Byte)"
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_001e: ldloc.2
IL_001f: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0024: conv.r8
IL_0025: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_002a: stloc.1
IL_002b: ldloca.s V_1
IL_002d: constrained. "System.ValueTuple(Of Integer, Double)"
IL_0033: callvirt "Function Object.ToString() As String"
IL_0038: call "Sub System.Console.WriteLine(String)"
IL_003d: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionNullable002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte) = (a:=100, b:=100)
Dim x as (integer, double)? = CType(i, (integer, double))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 3
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //i
(Integer, Double)? V_1, //x
System.ValueTuple(Of Byte, Byte) V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: call "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: stloc.2
IL_000f: ldloc.2
IL_0010: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0015: ldloc.2
IL_0016: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_001b: conv.r8
IL_001c: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_0021: call "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0026: ldloca.s V_1
IL_0028: constrained. "(Integer, Double)?"
IL_002e: callvirt "Function Object.ToString() As String"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionNullable003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte)? = (a:=100, b:=100)
Dim x = CType(i, (integer, double)?)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 87 (0x57)
.maxstack 3
.locals init ((x As Byte, y As Byte)? V_0, //i
(Integer, Double)? V_1, //x
(Integer, Double)? V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (x As Byte, y As Byte)?.get_HasValue() As Boolean"
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "(Integer, Double)?"
IL_0021: ldloc.2
IL_0022: br.s IL_0043
IL_0024: ldloca.s V_0
IL_0026: call "Function (x As Byte, y As Byte)?.GetValueOrDefault() As (x As Byte, y As Byte)"
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0032: ldloc.3
IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0038: conv.r8
IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0043: stloc.1
IL_0044: ldloca.s V_1
IL_0046: constrained. "(Integer, Double)?"
IL_004c: callvirt "Function Object.ToString() As String"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleConversionNullable004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as ValueTuple(of byte, byte)? = (a:=100, b:=100)
Dim x = CType(i, ValueTuple(of integer, double)?)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 87 (0x57)
.maxstack 3
.locals init ((Byte, Byte)? V_0, //i
(Integer, Double)? V_1, //x
(Integer, Double)? V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (Byte, Byte)?..ctor((Byte, Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (Byte, Byte)?.get_HasValue() As Boolean"
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "(Integer, Double)?"
IL_0021: ldloc.2
IL_0022: br.s IL_0043
IL_0024: ldloca.s V_0
IL_0026: call "Function (Byte, Byte)?.GetValueOrDefault() As (Byte, Byte)"
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0032: ldloc.3
IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0038: conv.r8
IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0043: stloc.1
IL_0044: ldloca.s V_1
IL_0046: constrained. "(Integer, Double)?"
IL_004c: callvirt "Function Object.ToString() As String"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
}
]]>)
End Sub
<Fact>
Public Sub ImplicitConversions02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = x
x = y
System.Console.WriteLine(x)
x = CType(CType(x, C1), (integer, integer))
System.Console.WriteLine(x)
End Sub
End Module
Class C1
Public Shared Widening Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 125 (0x7d)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0,
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_000e: conv.i8
IL_000f: ldloc.0
IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0015: conv.i8
IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001b: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0020: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_002c: ldloc.1
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0037: dup
IL_0038: box "System.ValueTuple(Of Integer, Integer)"
IL_003d: call "Sub System.Console.WriteLine(Object)"
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0049: conv.i8
IL_004a: ldloc.0
IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0050: conv.i8
IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0056: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_005b: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_0060: stloc.1
IL_0061: ldloc.1
IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0067: ldloc.1
IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0072: box "System.ValueTuple(Of Integer, Integer)"
IL_0077: call "Sub System.Console.WriteLine(Object)"
IL_007c: ret
}
]]>)
End Sub
<Fact>
Public Sub ExplicitConversions02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = CType(x, C1)
x = CTYpe(y, (integer, integer))
System.Console.WriteLine(x)
x = CType(CType(x, C1), (integer, integer))
System.Console.WriteLine(x)
End Sub
End Module
Class C1
Public Shared Narrowing Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 125 (0x7d)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0,
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_000e: conv.i8
IL_000f: ldloc.0
IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0015: conv.i8
IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001b: call "Function C1.op_Explicit((Long, Long)) As C1"
IL_0020: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)"
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_002c: ldloc.1
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0037: dup
IL_0038: box "System.ValueTuple(Of Integer, Integer)"
IL_003d: call "Sub System.Console.WriteLine(Object)"
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0049: conv.i8
IL_004a: ldloc.0
IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0050: conv.i8
IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0056: call "Function C1.op_Explicit((Long, Long)) As C1"
IL_005b: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)"
IL_0060: stloc.1
IL_0061: ldloc.1
IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0067: ldloc.1
IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0072: box "System.ValueTuple(Of Integer, Integer)"
IL_0077: call "Sub System.Console.WriteLine(Object)"
IL_007c: ret
}
]]>)
End Sub
<Fact>
Public Sub ImplicitConversions03()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = x
Dim x1 as (integer, integer)? = y
System.Console.WriteLine(x1)
x1 = CType(CType(x, C1), (integer, integer)?)
System.Console.WriteLine(x1)
End Sub
End Module
Class C1
Public Shared Widening Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 140 (0x8c)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, Integer) V_0, //x
C1 V_1, //y
System.ValueTuple(Of Integer, Integer) V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.1
IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0009: ldloc.0
IL_000a: stloc.2
IL_000b: ldloc.2
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: conv.i8
IL_0012: ldloc.2
IL_0013: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0018: conv.i8
IL_0019: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001e: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_002a: stloc.3
IL_002b: ldloc.3
IL_002c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0031: ldloc.3
IL_0032: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0037: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_003c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))"
IL_0041: box "(Integer, Integer)?"
IL_0046: call "Sub System.Console.WriteLine(Object)"
IL_004b: ldloc.0
IL_004c: stloc.2
IL_004d: ldloc.2
IL_004e: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0053: conv.i8
IL_0054: ldloc.2
IL_0055: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_005a: conv.i8
IL_005b: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0060: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0065: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_006a: stloc.3
IL_006b: ldloc.3
IL_006c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0071: ldloc.3
IL_0072: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0077: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_007c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))"
IL_0081: box "(Integer, Integer)?"
IL_0086: call "Sub System.Console.WriteLine(Object)"
IL_008b: ret
}
]]>)
End Sub
<Fact>
Public Sub ImplicitConversions04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (1, (1, (1, (1, (1, (1, 1))))))
Dim y as C1 = x
Dim x2 as (integer, integer) = y
System.Console.WriteLine(x2)
Dim x3 as (integer, (integer, integer)) = y
System.Console.WriteLine(x3)
Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y
System.Console.WriteLine(x12)
End Sub
End Module
Class C1
Private x as Byte
Public Shared Widening Operator CType(arg as (long, C1)) as C1
Dim result = new C1()
result.x = arg.Item2.x
return result
End Operator
Public Shared Widening Operator CType(arg as (long, long)) as C1
Dim result = new C1()
result.x = CByte(arg.Item2)
return result
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as C1)
Dim t = arg.x
arg.x += 1
return (CByte(t), arg)
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
Dim t1 = arg.x
arg.x += 1
Dim t2 = arg.x
arg.x += 1
return (CByte(t1), CByte(t2))
End Operator
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(1, 2)
(3, (4, 5))
(6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))
]]>)
End Sub
<Fact>
Public Sub ExplicitConversions04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (1, (1, (1, (1, (1, (1, 1))))))
Dim y as C1 = x
Dim x2 as (integer, integer) = y
System.Console.WriteLine(x2)
Dim x3 as (integer, (integer, integer)) = y
System.Console.WriteLine(x3)
Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y
System.Console.WriteLine(x12)
End Sub
End Module
Class C1
Private x as Byte
Public Shared Narrowing Operator CType(arg as (long, C1)) as C1
Dim result = new C1()
result.x = arg.Item2.x
return result
End Operator
Public Shared Narrowing Operator CType(arg as (long, long)) as C1
Dim result = new C1()
result.x = CByte(arg.Item2)
return result
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as C1)
Dim t = arg.x
arg.x += 1
return (CByte(t), arg)
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte)
Dim t1 = arg.x
arg.x += 1
Dim t2 = arg.x
arg.x += 1
return (CByte(t1), CByte(t2))
End Operator
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(1, 2)
(3, (4, 5))
(6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))
]]>)
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub Main()
Dim x1 As Byte = 300
Dim x2 As Byte() = { 300 }
Dim x3 As (Byte, Byte) = (300, 300)
Dim x4 As Byte? = 300
Dim x5 As Byte?() = { 300 }
Dim x6 As (Byte?, Byte?) = (300, 300)
Dim x7 As (Byte, Byte)? = (300, 300)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub M1 (x as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M1 (x as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M2 (x as Byte(), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M2 (x as Byte(), y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M3 (x as (Byte, Byte))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as (Short, Short))
System.Console.WriteLine("Short")
End Sub
Shared Sub M4 (x as (Byte, Byte), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M4 (x as (Byte, Byte), y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M5 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as Short?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M6 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as (Short?, Short?))
System.Console.WriteLine("Short")
End Sub
Shared Sub M7 (x as (Byte, Byte)?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Short, Short)?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M8 (x as (Byte, Byte)?, y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M8 (x as (Byte, Byte)?, y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub Main()
M1(70000)
M2({ 300 }, 70000)
M3((70000, 70000))
M4((300, 300), 70000)
M5(70000)
M6((70000, 70000))
M7((70000, 70000))
M8((300, 300), 70000)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Byte
Byte
Byte
Byte
Byte
Byte
Byte
Byte")
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub M1 (x as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M1 (x as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M2 (x as Byte(), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M2 (x as Byte(), y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M3 (x as (Byte, Byte))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as (Short, Short))
System.Console.WriteLine("Short")
End Sub
Shared Sub M4 (x as (Byte, Byte), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M4 (x as (Byte, Byte), y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M5 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as Short?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M6 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as (Short?, Short?))
System.Console.WriteLine("Short")
End Sub
Shared Sub M7 (x as (Byte, Byte)?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Short, Short)?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M8 (x as (Byte, Byte)?, y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M8 (x as (Byte, Byte)?, y as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub Main()
M1(70000)
M2({ 300 }, 70000)
M3((70000, 70000))
M4((300, 300), 70000)
M5(70000)
M6((70000, 70000))
M7((70000, 70000))
M8((300, 300), 70000)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Byte
Byte
Byte
Byte
Byte
Byte
Byte
Byte")
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub M1 (x as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M1 (x as Integer)
System.Console.WriteLine("Integer")
End Sub
Shared Sub M2 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M2 (x as Integer?)
System.Console.WriteLine("Integer")
End Sub
Shared Sub M3 (x as Byte())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as Integer())
System.Console.WriteLine("Integer")
End Sub
Shared Sub M4 (x as (Byte, Byte))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M4 (x as (Integer, Integer))
System.Console.WriteLine("Integer")
End Sub
Shared Sub M5 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as (Integer?, Integer?))
System.Console.WriteLine("Integer")
End Sub
Shared Sub M6 (x as (Byte, Byte)?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as (Integer, Integer)?)
System.Console.WriteLine("Integer")
End Sub
Shared Sub M7 (x as (Byte, Byte)())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Integer, Integer)())
System.Console.WriteLine("Integer")
End Sub
Shared Sub Main()
M1(1)
M2(1)
M3({1})
M4((1, 1))
M5((1, 1))
M6((1, 1))
M7({(1, 1)})
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Integer
Integer
Integer
Integer
Integer
Integer
Integer")
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub M1 (x as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M1 (x as Long)
System.Console.WriteLine("Long")
End Sub
Shared Sub M2 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M2 (x as Long?)
System.Console.WriteLine("Long")
End Sub
Shared Sub M3 (x as Byte())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as Long())
System.Console.WriteLine("Long")
End Sub
Shared Sub M4 (x as (Byte, Byte))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M4 (x as (Long, Long))
System.Console.WriteLine("Long")
End Sub
Shared Sub M5 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as (Long?, Long?))
System.Console.WriteLine("Long")
End Sub
Shared Sub M6 (x as (Byte, Byte)?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as (Long, Long)?)
System.Console.WriteLine("Long")
End Sub
Shared Sub M7 (x as (Byte, Byte)())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Long, Long)())
System.Console.WriteLine("Long")
End Sub
Shared Sub Main()
M1(1)
M2(1)
M3({1})
M4((1, 1))
M5((1, 1))
M6((1, 1))
M7({(1, 1)})
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Long
Long
Long
Long
Long
Long
Long")
End Sub
<Fact>
<WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")>
Public Sub NarrowingFromNumericConstant_06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub M2 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as Byte())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as Byte?())
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Byte, Byte)())
System.Console.WriteLine("Byte")
End Sub
Shared Sub Main()
Dim a as Byte? = 1
Dim b as Byte() = {1}
Dim c as (Byte?, Byte?) = (1, 1)
Dim d as Byte?() = {1}
Dim e as (Byte, Byte)() = {(1, 1)}
M2(1)
M3({1})
M5((1, 1))
M6({1})
M7({(1, 1)})
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Byte
Byte
Byte
Byte
Byte")
End Sub
<Fact>
<WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")>
Public Sub NarrowingFromNumericConstant_07()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub M1 (x as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M2 (x as Byte(), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M3 (x as (Byte, Byte))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M4 (x as (Byte, Byte), y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M6 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub M7 (x as (Byte, Byte)?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M8 (x as (Byte, Byte)?, y as Byte)
System.Console.WriteLine("Byte")
End Sub
Shared Sub Main()
M1(300)
M2({ 300 }, 300)
M3((300, 300))
M4((300, 300), 300)
M5(70000)
M6((70000, 70000))
M7((70000, 70000))
M8((300, 300), 300)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Byte
Byte
Byte
Byte
Byte
Byte
Byte
Byte")
End Sub
<Fact>
Public Sub NarrowingFromNumericConstant_08()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub Main()
Dim x00 As (Integer, Integer) = (1, 1)
Dim x01 As (Byte, Integer) = (1, 1)
Dim x02 As (Integer, Byte) = (1, 1)
Dim x03 As (Byte, Long) = (1, 1)
Dim x04 As (Long, Byte) = (1, 1)
Dim x05 As (Byte, Integer) = (300, 1)
Dim x06 As (Integer, Byte) = (1, 300)
Dim x07 As (Byte, Long) = (300, 1)
Dim x08 As (Long, Byte) = (1, 300)
Dim x09 As (Long, Long) = (1, 300)
Dim x10 As (Byte, Byte) = (1, 300)
Dim x11 As (Byte, Byte) = (300, 1)
Dim one As Integer = 1
Dim x12 As (Byte, Byte, Byte) = (one, 300, 1)
Dim x13 As (Byte, Byte, Byte) = (300, one, 1)
Dim x14 As (Byte, Byte, Byte) = (300, 1, one)
Dim x15 As (Byte, Byte) = (one, one)
Dim x16 As (Integer, (Byte, Integer)) = (1, (1, 1))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray()
AssertConversions(model, nodes(0), ConversionKind.Identity, ConversionKind.Identity, ConversionKind.Identity)
AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.Identity)
AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.Identity,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric)
AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(5), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.Identity)
AssertConversions(model, nodes(6), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.Identity,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric)
AssertConversions(model, nodes(8), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(9), ConversionKind.WideningTuple,
ConversionKind.WideningNumeric,
ConversionKind.WideningNumeric)
AssertConversions(model, nodes(10), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(11), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(12), ConversionKind.NarrowingTuple,
ConversionKind.NarrowingNumeric,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(13), ConversionKind.NarrowingTuple,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant)
AssertConversions(model, nodes(14), ConversionKind.NarrowingTuple,
ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.NarrowingNumeric)
AssertConversions(model, nodes(15), ConversionKind.NarrowingTuple,
ConversionKind.NarrowingNumeric,
ConversionKind.NarrowingNumeric)
AssertConversions(model, nodes(16), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant,
ConversionKind.Identity,
ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant)
End Sub
Private Shared Sub AssertConversions(model As SemanticModel, literal As TupleExpressionSyntax, aggregate As ConversionKind, ParamArray parts As ConversionKind())
If parts.Length > 0 Then
Assert.Equal(literal.Arguments.Count, parts.Length)
For i As Integer = 0 To parts.Length - 1
Assert.Equal(parts(i), model.GetConversion(literal.Arguments(i).Expression).Kind)
Next
End If
Assert.Equal(aggregate, model.GetConversion(literal).Kind)
End Sub
<Fact>
Public Sub Narrowing_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub M2 (x as Byte?)
System.Console.WriteLine("Byte")
End Sub
Shared Sub M5 (x as (Byte?, Byte?))
System.Console.WriteLine("Byte")
End Sub
Shared Sub Main()
Dim x as integer = 1
Dim a as Byte? = x
Dim b as (Byte?, Byte?) = (x, x)
M2(x)
M5((x, x))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim a as Byte? = x
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim b as (Byte?, Byte?) = (x, x)
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim b as (Byte?, Byte?) = (x, x)
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
M2(x)
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
M5((x, x))
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
M5((x, x))
~
</expected>)
End Sub
<Fact>
Public Sub Narrowing_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub Main()
Dim x as integer = 1
Dim x1 = CType(x, Byte)
Dim x2 = CType(x, Byte?)
Dim x3 = CType((x, x), (Byte, Integer))
Dim x4 = CType((x, x), (Byte?, Integer?))
Dim x5 = CType((x, x), (Byte, Integer)?)
Dim x6 = CType((x, x), (Byte?, Integer?)?)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp)
End Sub
<Fact>
Public Sub Narrowing_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub Main()
Dim x as (Integer, Integer) = (1, 1)
Dim x3 = CType(x, (Byte, Integer))
Dim x4 = CType(x, (Byte?, Integer?))
Dim x5 = CType(x, (Byte, Integer)?)
Dim x6 = CType(x, (Byte?, Integer?)?)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp)
End Sub
<Fact>
Public Sub Narrowing_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub Main()
Dim x as (Integer, Integer) = (1, 1)
Dim x3 as (Byte, Integer) = x
Dim x4 as (Byte?, Integer?) = x
Dim x5 as (Byte, Integer)? = x
Dim x6 as (Byte?, Integer?)?= x
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp,
<expected>
BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)'.
Dim x3 as (Byte, Integer) = x
~
BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)'.
Dim x4 as (Byte?, Integer?) = x
~
BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)?'.
Dim x5 as (Byte, Integer)? = x
~
BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)?'.
Dim x6 as (Byte?, Integer?)?= x
~
</expected>)
End Sub
<Fact>
Public Sub OverloadResolution_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub M1 (x as Short)
System.Console.WriteLine("Short")
End Sub
Shared Sub M1 (x as Integer)
System.Console.WriteLine("Integer")
End Sub
Shared Sub M2 (x as Short?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M2 (x as Integer?)
System.Console.WriteLine("Integer")
End Sub
Shared Sub M3 (x as (Short, Short))
System.Console.WriteLine("Short")
End Sub
Shared Sub M3(x as (Integer, Integer))
System.Console.WriteLine("Integer")
End Sub
Shared Sub M4 (x as (Short?, Short?))
System.Console.WriteLine("Short")
End Sub
Shared Sub M4(x as (Integer?, Integer?))
System.Console.WriteLine("Integer")
End Sub
Shared Sub M5 (x as (Short, Short)?)
System.Console.WriteLine("Short")
End Sub
Shared Sub M5(x as (Integer, Integer)?)
System.Console.WriteLine("Integer")
End Sub
Shared Sub Main()
Dim x as Byte = 1
M1(x)
M2(x)
M3((x, x))
M4((x, x))
M5((x, x))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"Short
Short
Short
Short
Short")
End Sub
<Fact>
Public Sub FailedDueToNumericOverflow_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub Main()
Dim x1 As Byte = 300
Dim x2 as (Integer, Byte) = (300, 300)
Dim x3 As Byte? = 300
Dim x4 as (Integer?, Byte?) = (300, 300)
Dim x5 as (Integer, Byte)? = (300, 300)
Dim x6 as (Integer?, Byte?)? = (300, 300)
System.Console.WriteLine(x1)
System.Console.WriteLine(x2)
System.Console.WriteLine(x3)
System.Console.WriteLine(x4)
System.Console.WriteLine(x5)
System.Console.WriteLine(x6)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp, <expected></expected>)
CompileAndVerify(comp, expectedOutput:=
"44
(300, 44)
44
(300, 44)
(300, 44)
(300, 44)")
comp = comp.WithOptions(comp.Options.WithOverflowChecks(True))
AssertTheseDiagnostics(comp,
<expected>
BC30439: Constant expression not representable in type 'Byte'.
Dim x1 As Byte = 300
~~~
BC30439: Constant expression not representable in type 'Byte'.
Dim x2 as (Integer, Byte) = (300, 300)
~~~
BC30439: Constant expression not representable in type 'Byte?'.
Dim x3 As Byte? = 300
~~~
BC30439: Constant expression not representable in type 'Byte?'.
Dim x4 as (Integer?, Byte?) = (300, 300)
~~~
BC30439: Constant expression not representable in type 'Byte'.
Dim x5 as (Integer, Byte)? = (300, 300)
~~~
BC30439: Constant expression not representable in type 'Byte?'.
Dim x6 as (Integer?, Byte?)? = (300, 300)
~~~
</expected>)
End Sub
<Fact>
Public Sub MethodTypeInference001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((1,"q")))
End Sub
Function Test(of T1, T2)(x as (T1, T2)) as (T1, T2)
Console.WriteLine(Gettype(T1))
Console.WriteLine(Gettype(T2))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Int32
System.String
(1, q)
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim v = (new Object(),"q")
Test(v)
System.Console.WriteLine(v)
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Object
(System.Object, q)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 51 (0x33)
.maxstack 3
.locals init (System.ValueTuple(Of Object, String) V_0)
IL_0000: newobj "Sub Object..ctor()"
IL_0005: ldstr "q"
IL_000a: newobj "Sub System.ValueTuple(Of Object, String)..ctor(Object, String)"
IL_000f: dup
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldfld "System.ValueTuple(Of Object, String).Item1 As Object"
IL_0017: ldloc.0
IL_0018: ldfld "System.ValueTuple(Of Object, String).Item2 As String"
IL_001d: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)"
IL_0022: call "Function C.Test(Of Object)((Object, Object)) As (Object, Object)"
IL_0027: pop
IL_0028: box "System.ValueTuple(Of Object, String)"
IL_002d: call "Sub System.Console.WriteLine(Object)"
IL_0032: ret
}
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference002Err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim v = (new Object(),"q")
Test(v)
System.Console.WriteLine(v)
TestRef(v)
System.Console.WriteLine(v)
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
Function TestRef(of T)(ByRef x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
x.Item1 = x.Item2
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function TestRef(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
TestRef(v)
~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub MethodTypeInference003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((Nothing,"q")))
System.Console.WriteLine(Test(("q", Nothing)))
System.Console.WriteLine(Test1((Nothing, Nothing), (Nothing,"q")))
System.Console.WriteLine(Test1(("q", Nothing), (Nothing, Nothing)))
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
Function Test1(of T)(x as (T, T), y as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.String
(, q)
System.String
(q, )
System.String
(, )
System.String
(q, )
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim q = "q"
Dim a As Object = "a"
System.Console.WriteLine(Test((q, a)))
System.Console.WriteLine(q)
System.Console.WriteLine(a)
System.Console.WriteLine(Test((Ps, Po)))
System.Console.WriteLine(q)
System.Console.WriteLine(a)
End Sub
Function Test(Of T)(ByRef x As (T, T)) As (T, T)
Console.WriteLine(GetType(T))
x.Item1 = x.Item2
Return x
End Function
Public Property Ps As String
Get
Return "q"
End Get
Set(value As String)
System.Console.WriteLine("written1 !!!")
End Set
End Property
Public Property Po As Object
Get
Return "a"
End Get
Set(value As Object)
System.Console.WriteLine("written2 !!!")
End Set
End Property
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Object
(a, a)
q
a
System.Object
(a, a)
q
a
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference004a()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((new Object(),"q")))
System.Console.WriteLine(Test1((new Object(),"q")))
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
Function Test1(of T)(x as T) as T
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Object
(System.Object, q)
System.ValueTuple`2[System.Object,System.String]
(System.Object, q)
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference004Err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim q = "q"
Dim a as object = "a"
Dim t = (q, a)
System.Console.WriteLine(Test(t))
System.Console.WriteLine(q)
System.Console.WriteLine(a)
End Sub
Function Test(of T)(byref x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
x.Item1 = x.Item2
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function Test(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
System.Console.WriteLine(Test(t))
~~~~
</errors>)
End Sub
<Fact>
Public Sub MethodTypeInference005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of String) = {1, 2}
Dim t = (ie, ie)
Test(t, New Object)
Test((ie, ie), New Object)
End Sub
Sub Test(Of T)(a1 As (IEnumerable(Of T), IEnumerable(Of T)), a2 As T)
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Object
System.Object
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of Integer) = {1, 2}
Dim t = (ie, ie)
Test(t)
Test((1, 1))
End Sub
Sub Test(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Collections.Generic.IEnumerable`1[System.Int32]
System.Int32
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of Integer) = {1, 2}
Dim t = (ie, ie)
Test(t)
Test((1, 1))
End Sub
Sub Test(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Collections.Generic.IEnumerable`1[System.Int32]
System.Int32
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference008()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim t = (1, 1L)
' these are valid
Test1(t)
Test1((1, 1L))
End Sub
Sub Test1(Of T)(f1 As (T, T))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.Int64
System.Int64
]]>)
End Sub
<Fact>
Public Sub MethodTypeInference008Err()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim t = (1, 1L)
' these are valid
Test1(t)
Test1((1, 1L))
' these are not
Test2(t)
Test2((1, 1L))
End Sub
Sub Test1(Of T)(f1 As (T, T))
System.Console.WriteLine(GetType(T))
End Sub
Sub Test2(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test2(t)
~~~~~
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test2((1, 1L))
~~~~~
</errors>)
End Sub
<Fact>
Public Sub Inference04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test( Function(x)x.y )
Test( Function(x)x.bob )
End Sub
Sub Test(of T)(x as Func(of (x as Byte, y As Byte), T))
System.Console.WriteLine("first")
System.Console.WriteLine(x((2,3)).ToString())
End Sub
Sub Test(of T)(x as Func(of (alice as integer, bob as integer), T))
System.Console.WriteLine("second")
System.Console.WriteLine(x((4,5)).ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
first
3
second
5
]]>)
End Sub
<Fact>
Public Sub Inference07()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x)(x, x), Function(t)1)
Test1(Function(x)(x, x), Function(t)1)
Test2((a:= 1, b:= 2), Function(t)(t.a, t.b))
End Sub
Sub Test(Of U)(f1 as Func(of Integer, ValueTuple(Of U, U)), f2 as Func(Of ValueTuple(Of U, U), Integer))
System.Console.WriteLine(f2(f1(1)))
End Sub
Sub Test1(of U)(f1 As Func(of integer, (U, U)), f2 as Func(Of (U, U), integer))
System.Console.WriteLine(f2(f1(1)))
End Sub
Sub Test2(of U, T)(f1 as U , f2 As Func(Of U, (x as T, y As T)))
System.Console.WriteLine(f2(f1).y)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
1
1
2
]]>)
End Sub
<Fact>
Public Sub InferenceChain001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x As (Integer, Integer)) (x, x), Function(t) (t, t))
End Sub
Sub Test(Of T, U, V)(f1 As Func(Of (T,T), (U,U)), f2 As Func(Of (U,U), (V,V)))
System.Console.WriteLine(f2(f1(Nothing)))
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine(GetType(V))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
System.Int32
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Int32],System.ValueTuple`2[System.Int32,System.Int32]]
]]>)
End Sub
<Fact>
Public Sub InferenceChain002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x As (Integer, Object)) (x, x), Function(t) (t, t))
End Sub
Sub Test(Of T, U, V)(ByRef f1 As Func(Of (T, T), (U, U)), ByRef f2 As Func(Of (U, U), (V, V)))
System.Console.WriteLine(f2(f1(Nothing)))
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine(GetType(V))
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(((0, ), (0, )), ((0, ), (0, )))
System.Object
System.ValueTuple`2[System.Int32,System.Object]
System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Object],System.ValueTuple`2[System.Int32,System.Object]]
]]>)
End Sub
<Fact>
Public Sub SimpleTupleNested()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = (1, (2, (3, 4)).ToString())
System.Console.Write(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, (2, (3, 4)))]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 54 (0x36)
.maxstack 5
.locals init (System.ValueTuple(Of Integer, String) V_0, //x
System.ValueTuple(Of Integer, (Integer, Integer)) V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: ldc.i4.3
IL_0005: ldc.i4.4
IL_0006: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_000b: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))"
IL_0010: stloc.1
IL_0011: ldloca.s V_1
IL_0013: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))"
IL_0019: callvirt "Function Object.ToString() As String"
IL_001e: call "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_0023: ldloca.s V_0
IL_0025: constrained. "System.ValueTuple(Of Integer, String)"
IL_002b: callvirt "Function Object.ToString() As String"
IL_0030: call "Sub System.Console.Write(String)"
IL_0035: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleUnderlyingItemAccess()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = (1, 2)
System.Console.WriteLine(x.Item2.ToString())
x.Item1 = 40
System.Console.WriteLine(x.Item1 + x.Item2)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2
42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 54 (0x36)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0009: ldloca.s V_0
IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0010: call "Function Integer.ToString() As String"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.s 40
IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0023: ldloc.0
IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0029: ldloc.0
IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_002f: add.ovf
IL_0030: call "Sub System.Console.WriteLine(Integer)"
IL_0035: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleUnderlyingItemAccess01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = (A:=1, B:=2)
System.Console.WriteLine(x.Item2.ToString())
x.Item1 = 40
System.Console.WriteLine(x.Item1 + x.Item2)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2
42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 54 (0x36)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0009: ldloca.s V_0
IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0010: call "Function Integer.ToString() As String"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.s 40
IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0023: ldloc.0
IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0029: ldloc.0
IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_002f: add.ovf
IL_0030: call "Sub System.Console.WriteLine(Integer)"
IL_0035: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleItemAccess()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = (A:=1, B:=2)
System.Console.WriteLine(x.Item2.ToString())
x.A = 40
System.Console.WriteLine(x.A + x.B)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2
42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 54 (0x36)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0009: ldloca.s V_0
IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0010: call "Function Integer.ToString() As String"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.s 40
IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0023: ldloc.0
IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0029: ldloc.0
IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_002f: add.ovf
IL_0030: call "Sub System.Console.WriteLine(Integer)"
IL_0035: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleItemAccess01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = (A:=1, B:=(C:=2, D:= 3))
System.Console.WriteLine(x.B.C.ToString())
x.B.D = 39
System.Console.WriteLine(x.A + x.B.C + x.B.D)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2
42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 87 (0x57)
.maxstack 4
.locals init (System.ValueTuple(Of Integer, (C As Integer, D As Integer)) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: ldc.i4.3
IL_0005: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_000a: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As Integer))..ctor(Integer, (C As Integer, D As Integer))"
IL_000f: ldloca.s V_0
IL_0011: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)"
IL_0016: ldflda "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_001b: call "Function Integer.ToString() As String"
IL_0020: call "Sub System.Console.WriteLine(String)"
IL_0025: ldloca.s V_0
IL_0027: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)"
IL_002c: ldc.i4.s 39
IL_002e: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0033: ldloc.0
IL_0034: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item1 As Integer"
IL_0039: ldloc.0
IL_003a: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)"
IL_003f: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0044: add.ovf
IL_0045: ldloc.0
IL_0046: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)"
IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0050: add.ovf
IL_0051: call "Sub System.Console.WriteLine(Integer)"
IL_0056: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleTypeDeclaration()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As (Integer, String, Integer) = (1, "hello", 2)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello, 2)]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 4
.locals init (System.ValueTuple(Of Integer, String, Integer) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldstr "hello"
IL_0008: ldc.i4.2
IL_0009: call "Sub System.ValueTuple(Of Integer, String, Integer)..ctor(Integer, String, Integer)"
IL_000e: ldloca.s V_0
IL_0010: constrained. "System.ValueTuple(Of Integer, String, Integer)"
IL_0016: callvirt "Function Object.ToString() As String"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleTypeMismatch_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, String) = (1, "hello", 2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Integer, String, Integer)' cannot be converted to '(Integer, String)'.
Dim x As (Integer, String) = (1, "hello", 2)
~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleTypeMismatch_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, String) = (1, Nothing, 2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(Integer, String)'.
Dim x As (Integer, String) = (1, Nothing, 2)
~~~~~~~~~~~~~~~
</errors>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub LongTupleTypeMismatch()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8)
Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8)
End Sub
End Module
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported.
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported.
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported.
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported.
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported.
Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported.
Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported.
Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported.
Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleTypeWithLateDiscoveredName()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, A As String) = (1, "hello", C:=2)
End Sub
End Module
]]></file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Integer, String, C As Integer)' cannot be converted to '(Integer, A As String)'.
Dim x As (Integer, A As String) = (1, "hello", C:=2)
~~~~~~~~~~~~~~~~~~
</errors>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, ""hello"", C:=2)", node.ToString())
Assert.Equal("(System.Int32, System.String, C As System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type
Assert.Equal("(System.Int32, A As System.String)", xSymbol.ToTestDisplayString())
Assert.True(xSymbol.IsTupleType)
Assert.False(DirectCast(xSymbol, INamedTypeSymbol).IsSerializable)
Assert.Equal({"System.Int32", "System.String"}, xSymbol.TupleElementTypes.SelectAsArray(Function(t) t.ToTestDisplayString()))
Assert.Equal({Nothing, "A"}, xSymbol.TupleElementNames)
End Sub
<Fact>
Public Sub TupleTypeDeclarationWithNames()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As (A As Integer, B As String) = (1, "hello")
System.Console.WriteLine(x.A.ToString())
System.Console.WriteLine(x.B.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1
hello]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleDictionary01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Class C
Shared Sub Main()
Dim k = (1, 2)
Dim v = (A:=1, B:=(C:=2, D:=(E:=3, F:=4)))
Dim d = Test(k, v)
System.Console.Write(d((1, 2)).B.D.Item2)
End Sub
Shared Function Test(Of K, V)(key As K, value As V) As Dictionary(Of K, V)
Dim d = new Dictionary(Of K, V)()
d(key) = value
return d
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[4]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 67 (0x43)
.maxstack 6
.locals init (System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))) V_0) //v
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: ldloca.s V_0
IL_0009: ldc.i4.1
IL_000a: ldc.i4.2
IL_000b: ldc.i4.3
IL_000c: ldc.i4.4
IL_000d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0012: newobj "Sub System.ValueTuple(Of Integer, (E As Integer, F As Integer))..ctor(Integer, (E As Integer, F As Integer))"
IL_0017: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer)))..ctor(Integer, (C As Integer, D As (E As Integer, F As Integer)))"
IL_001c: ldloc.0
IL_001d: call "Function C.Test(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))((Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))) As System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))"
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0029: callvirt "Function System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))).get_Item((Integer, Integer)) As (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))"
IL_002e: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))).Item2 As (C As Integer, D As (E As Integer, F As Integer))"
IL_0033: ldfld "System.ValueTuple(Of Integer, (E As Integer, F As Integer)).Item2 As (E As Integer, F As Integer)"
IL_0038: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_003d: call "Sub System.Console.Write(Integer)"
IL_0042: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleLambdaCapture01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
System.Console.Write(Test(42))
End Sub
Public Shared Function Test(Of T)(a As T) As T
Dim x = (f1:=a, f2:=a)
Dim f As System.Func(Of T) = Function() x.f2
return f()
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)"
IL_0006: ldfld "System.ValueTuple(Of $CLS0, $CLS0).Item2 As $CLS0"
IL_000b: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleLambdaCapture02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
System.Console.Write(Test(42))
End Sub
Shared Function Test(Of T)(a As T) As String
Dim x = (f1:=a, f2:=a)
Dim f As System.Func(Of String) = Function() x.ToString()
Return f()
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(42, 42)]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)"
IL_0006: constrained. "System.ValueTuple(Of $CLS0, $CLS0)"
IL_000c: callvirt "Function Object.ToString() As String"
IL_0011: ret
}
]]>)
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/13298")>
Public Sub TupleLambdaCapture03()
' This test crashes in TypeSubstitution
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
System.Console.Write(Test(42))
End Sub
Shared Function Test(Of T)(a As T) As T
Dim x = (f1:=a, f2:=b)
Dim f As System.Func(Of T) = Function() x.Test(a)
Return f()
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Function Test(Of U)(val As U) As U
Return val
End Function
End Structure
End Namespace
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
]]>)
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")>
Public Sub TupleLambdaCapture04()
' this test crashes in TypeSubstitution
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
System.Console.Write(Test(42))
End Sub
Shared Function Test(Of T)(a As T) As T
Dim x = (f1:=1, f2:=2)
Dim f As System.Func(Of T) = Function() x.Test(a)
Return f()
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Function Test(Of U)(val As U) As U
Return val
End Function
End Structure
End Namespace
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
]]>)
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")>
Public Sub TupleLambdaCapture05()
' this test crashes in TypeSubstitution
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
System.Console.Write(Test(42))
End Sub
Shared Function Test(Of T)(a As T) As T
Dim x = (f1:=a, f2:=a)
Dim f As System.Func(Of T) = Function() x.P1
Return f()
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public ReadOnly Property P1 As T1
Get
Return Item1
End Get
End Property
End Structure
End Namespace
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("Module1.Main", <![CDATA[
]]>)
End Sub
<Fact>
Public Sub TupleAsyncCapture01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class C
Shared Sub Main()
Console.Write(Test(42).Result)
End Sub
Shared Async Function Test(Of T)(a As T) As Task(Of T)
Dim x = (f1:=a, f2:=a)
Await Task.Yield()
Return x.f1
End Function
End Class
</file>
</compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[
{
// Code size 204 (0xcc)
.maxstack 3
.locals init (SM$T V_0,
Integer V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0058
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T"
IL_0011: ldarg.0
IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T"
IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)"
IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)"
IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0026: stloc.3
IL_0027: ldloca.s V_3
IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_002e: stloc.2
IL_002f: ldloca.s V_2
IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0036: brtrue.s IL_0074
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.1
IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0041: ldarg.0
IL_0042: ldloc.2
IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0048: ldarg.0
IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)"
IL_004e: ldloca.s V_2
IL_0050: ldarg.0
IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))"
IL_0056: leave.s IL_00cb
IL_0058: ldarg.0
IL_0059: ldc.i4.m1
IL_005a: dup
IL_005b: stloc.1
IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0061: ldarg.0
IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0067: stloc.2
IL_0068: ldarg.0
IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0074: ldloca.s V_2
IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_007b: ldloca.s V_2
IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0083: ldarg.0
IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)"
IL_0089: ldfld "System.ValueTuple(Of SM$T, SM$T).Item1 As SM$T"
IL_008e: stloc.0
IL_008f: leave.s IL_00b5
}
catch System.Exception
{
IL_0091: dup
IL_0092: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0097: stloc.s V_4
IL_0099: ldarg.0
IL_009a: ldc.i4.s -2
IL_009c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_00a1: ldarg.0
IL_00a2: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)"
IL_00a7: ldloc.s V_4
IL_00a9: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetException(System.Exception)"
IL_00ae: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00b3: leave.s IL_00cb
}
IL_00b5: ldarg.0
IL_00b6: ldc.i4.s -2
IL_00b8: dup
IL_00b9: stloc.1
IL_00ba: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_00bf: ldarg.0
IL_00c0: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)"
IL_00c5: ldloc.0
IL_00c6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetResult(SM$T)"
IL_00cb: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleAsyncCapture02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class C
Shared Sub Main()
Console.Write(Test(42).Result)
End Sub
Shared Async Function Test(Of T)(a As T) As Task(Of String)
Dim x = (f1:=a, f2:=a)
Await Task.Yield()
Return x.ToString()
End Function
End Class
</file>
</compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[(42, 42)]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[
{
// Code size 210 (0xd2)
.maxstack 3
.locals init (String V_0,
Integer V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0058
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T"
IL_0011: ldarg.0
IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T"
IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)"
IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)"
IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0026: stloc.3
IL_0027: ldloca.s V_3
IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_002e: stloc.2
IL_002f: ldloca.s V_2
IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0036: brtrue.s IL_0074
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.1
IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0041: ldarg.0
IL_0042: ldloc.2
IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0048: ldarg.0
IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_004e: ldloca.s V_2
IL_0050: ldarg.0
IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))"
IL_0056: leave.s IL_00d1
IL_0058: ldarg.0
IL_0059: ldc.i4.m1
IL_005a: dup
IL_005b: stloc.1
IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_0061: ldarg.0
IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0067: stloc.2
IL_0068: ldarg.0
IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0074: ldloca.s V_2
IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_007b: ldloca.s V_2
IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0083: ldarg.0
IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)"
IL_0089: constrained. "System.ValueTuple(Of SM$T, SM$T)"
IL_008f: callvirt "Function Object.ToString() As String"
IL_0094: stloc.0
IL_0095: leave.s IL_00bb
}
catch System.Exception
{
IL_0097: dup
IL_0098: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_009d: stloc.s V_4
IL_009f: ldarg.0
IL_00a0: ldc.i4.s -2
IL_00a2: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_00a7: ldarg.0
IL_00a8: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_00ad: ldloc.s V_4
IL_00af: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)"
IL_00b4: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00b9: leave.s IL_00d1
}
IL_00bb: ldarg.0
IL_00bc: ldc.i4.s -2
IL_00be: dup
IL_00bf: stloc.1
IL_00c0: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer"
IL_00c5: ldarg.0
IL_00c6: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_00cb: ldloc.0
IL_00cc: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)"
IL_00d1: ret
}
]]>)
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")>
Public Sub TupleAsyncCapture03()
' this test crashes in TypeSubstitution
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class C
Shared Sub Main()
Console.Write(Test(42).Result)
End Sub
Shared Async Function Test(Of T)(a As T) As Task(Of String)
Dim x = (f1:=a, f2:=a)
Await Task.Yield()
Return x.Test(a)
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Function Test(Of U)(val As U) As U
Return val
End Function
End Structure
End Namespace
</file>
</compilation>, references:={MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[
]]>)
End Sub
<Fact>
Public Sub LongTupleWithSubstitution()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class C
Shared Sub Main()
Console.Write(Test(42).Result)
End Sub
Shared Async Function Test(Of T)(a As T) As Task(Of T)
Dim x = (f1:=1, f2:=2, f3:=3, f4:=4, f5:=5, f6:=6, f7:=7, f8:=a)
Await Task.Yield()
Return x.f8
End Function
End Class
</file>
</compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleUsageWithoutTupleLibrary()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, String) = (1, "hello")
End Sub
End Module
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim x As (Integer, String) = (1, "hello")
~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim x As (Integer, String) = (1, "hello")
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleUsageWithMissingTupleMembers()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Integer, String) = (1, 2)
End Sub
End Module
Namespace System
Public Structure ValueTuple(Of T1, T2)
End Structure
End Namespace
]]></file>
</compilation>)
comp.AssertTheseEmitDiagnostics(
<errors>
BC35000: Requested operation is not available because the runtime library function 'ValueTuple..ctor' is not defined.
Dim x As (Integer, String) = (1, 2)
~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleWithDuplicateNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37262: Tuple element names must be unique.
Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2)
~
BC37262: Tuple element names must be unique.
Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2)
~
BC37262: Tuple element names must be unique.
Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2)
~
</errors>)
End Sub
<Fact>
Public Sub TupleWithDuplicateReservedNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello")
Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello")
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37261: Tuple element name 'Item1' is only allowed at position 1.
Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello")
~~~~~
BC37261: Tuple element name 'Item1' is only allowed at position 1.
Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello")
~~~~~
BC37261: Tuple element name 'Item2' is only allowed at position 2.
Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello")
~~~~~
BC37261: Tuple element name 'Item2' is only allowed at position 2.
Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello")
~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleWithNonReservedNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37261: Tuple element name 'Item10' is only allowed at position 10.
Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3)
~~~~~~
BC37261: Tuple element name 'Item1' is only allowed at position 1.
Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3)
~~~~~
BC37261: Tuple element name 'Item10' is only allowed at position 10.
Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3)
~~~~~~
</errors>)
End Sub
<Fact>
Public Sub DefaultValueForTuple()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As (a As Integer, b As String) = (1, "hello")
x = Nothing
System.Console.WriteLine(x.a)
System.Console.WriteLine(If(x.b, "null"))
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0
null]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleWithDuplicateMemberNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37262: Tuple element names must be unique.
Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2)
~
BC37262: Tuple element names must be unique.
Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2)
~
</errors>)
End Sub
<Fact>
Public Sub TupleWithReservedMemberNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) =
(Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad")
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37261: Tuple element name 'Item3' is only allowed at position 3.
Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) =
~~~~~
BC37261: Tuple element name 'Item2' is only allowed at position 2.
Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) =
~~~~~
BC37260: Tuple element name 'Rest' is disallowed at any position.
Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) =
~~~~
BC37261: Tuple element name 'Item2' is only allowed at position 2.
(Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad")
~~~~~
BC37261: Tuple element name 'Item4' is only allowed at position 4.
(Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad")
~~~~~
BC37260: Tuple element name 'Rest' is disallowed at any position.
(Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad")
~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleWithExistingUnderlyingMemberNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37260: Tuple element name 'CompareTo' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~~~~~~
BC37260: Tuple element name 'Deconstruct' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~~~~~~~~
BC37260: Tuple element name 'Equals' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~~~
BC37260: Tuple element name 'GetHashCode' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~~~~~~~~
BC37260: Tuple element name 'Rest' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~
BC37260: Tuple element name 'ToString' is disallowed at any position.
Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10)
~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub LongTupleDeclaration()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer) =
(1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5)
System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12}")
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>,
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0)
Assert.Equal("x As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _
+ "System.String, System.Int32, System.Int32, System.Int32, System.Int32)",
model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LongTupleDeclarationWithNames()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As (a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer, g As Integer, _
h As String, i As Integer, j As Integer, k As Integer, l As Integer) =
(1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5)
System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l}")
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>,
sourceSymbolValidator:=Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0)
Assert.Equal("x As (a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, " _
+ "e As System.Int32, f As System.Int32, g As System.Int32, h As System.String, " _
+ "i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32)",
model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<ConditionalFact(GetType(NoIOperationValidation))>
Public Sub HugeTupleCreationParses()
Dim b = New StringBuilder()
b.Append("(")
For i As Integer = 0 To 2000
b.Append("1, ")
Next
b.Append("1)")
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x = <%= b.ToString() %>
End Sub
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertNoDiagnostics()
End Sub
<ConditionalFact(GetType(NoIOperationValidation))>
Public Sub HugeTupleDeclarationParses()
Dim b = New StringBuilder()
b.Append("(")
For i As Integer = 0 To 3000
b.Append("Integer, ")
Next
b.Append("Integer)")
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As <%= b.ToString() %>;
End Sub
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
End Sub
<Fact>
<WorkItem(13302, "https://github.com/dotnet/roslyn/issues/13302")>
Public Sub GenericTupleWithoutTupleLibrary_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Shared Sub Main()
Dim x = M(Of Integer, Boolean)()
System.Console.Write($"{x.first} {x.second}")
End Sub
Public Shared Function M(Of T1, T2)() As (first As T1, second As T2)
return (Nothing, Nothing)
End Function
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Public Shared Function M(Of T1, T2)() As (first As T1, second As T2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
Public Shared Function M(Of T1, T2)() As (first As T1, second As T2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
return (Nothing, Nothing)
~~~~~~~~~~~~~~~~~~
</errors>)
Dim mTuple = DirectCast(comp.GetMember(Of MethodSymbol)("C.M").ReturnType, NamedTypeSymbol)
Assert.True(mTuple.IsTupleType)
Assert.Equal(TypeKind.Error, mTuple.TupleUnderlyingType.TypeKind)
Assert.Equal(SymbolKind.ErrorType, mTuple.TupleUnderlyingType.Kind)
Assert.IsAssignableFrom(Of ErrorTypeSymbol)(mTuple.TupleUnderlyingType)
Assert.Equal(TypeKind.Struct, mTuple.TypeKind)
'AssertTupleTypeEquality(mTuple)
Assert.False(mTuple.IsImplicitlyDeclared)
'Assert.Equal("Predefined type 'System.ValueTuple`2' is not defined or imported", mTuple.GetUseSiteDiagnostic().GetMessage(CultureInfo.InvariantCulture))
Assert.Null(mTuple.BaseType)
Assert.False(DirectCast(mTuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Any())
Dim mFirst = DirectCast(mTuple.GetMembers("first").Single(), FieldSymbol)
Assert.IsType(Of TupleErrorFieldSymbol)(mFirst)
Assert.True(mFirst.IsTupleField)
Assert.Equal("first", mFirst.Name)
Assert.Same(mFirst, mFirst.OriginalDefinition)
Assert.True(mFirst.Equals(mFirst))
Assert.Null(mFirst.TupleUnderlyingField)
Assert.Null(mFirst.AssociatedSymbol)
Assert.Same(mTuple, mFirst.ContainingSymbol)
Assert.True(mFirst.CustomModifiers.IsEmpty)
Assert.True(mFirst.GetAttributes().IsEmpty)
'Assert.Null(mFirst.GetUseSiteDiagnostic())
Assert.False(mFirst.Locations.IsEmpty)
Assert.Equal("first As T1", mFirst.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.False(mFirst.IsImplicitlyDeclared)
Assert.Null(mFirst.TypeLayoutOffset)
Dim mItem1 = DirectCast(mTuple.GetMembers("Item1").Single(), FieldSymbol)
Assert.IsType(Of TupleErrorFieldSymbol)(mItem1)
Assert.True(mItem1.IsTupleField)
Assert.Equal("Item1", mItem1.Name)
Assert.Same(mItem1, mItem1.OriginalDefinition)
Assert.True(mItem1.Equals(mItem1))
Assert.Null(mItem1.TupleUnderlyingField)
Assert.Null(mItem1.AssociatedSymbol)
Assert.Same(mTuple, mItem1.ContainingSymbol)
Assert.True(mItem1.CustomModifiers.IsEmpty)
Assert.True(mItem1.GetAttributes().IsEmpty)
'Assert.Null(mItem1.GetUseSiteDiagnostic())
Assert.True(mItem1.Locations.IsEmpty)
Assert.True(mItem1.IsImplicitlyDeclared)
Assert.Null(mItem1.TypeLayoutOffset)
End Sub
<Fact>
<WorkItem(13300, "https://github.com/dotnet/roslyn/issues/13300")>
Public Sub GenericTupleWithoutTupleLibrary_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9)
Throw New System.NotSupportedException()
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
End Structure
End Namespace
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported.
Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub GenericTuple()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x = M(Of Integer, Boolean)()
System.Console.Write($"{x.first} {x.second}")
End Sub
Shared Function M(Of T1, T2)() As (first As T1, second As T2)
Return (Nothing, Nothing)
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 False]]>)
End Sub
<Fact>
Public Sub LongTupleCreation()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5, 6, 7, "Bob", 2, 3)
System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} " _
+ $"{x.Item9} {x.Item10} {x.Item11} {x.Item12} {x.Item13} {x.Item14} {x.Item15} {x.Item16} {x.Item17}")
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>,
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _
+ "System.String, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _
+ "System.String, System.Int32, System.Int32)",
model.GetTypeInfo(x).Type.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleInLambda()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim f As System.Action(Of (Integer, String)) = Sub(x As (Integer, String)) System.Console.Write($"{x.Item1} {x.Item2}")
f((42, "Alice"))
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleWithNamesInLambda()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim f As System.Action(Of (Integer, String)) = Sub(x As (a As Integer, b As String)) System.Console.Write($"{x.Item1} {x.Item2}")
f((c:=42, d:="Alice"))
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>)
End Sub
<Fact>
Public Sub TupleInProperty()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Property P As (a As Integer, b As String)
Shared Sub Main()
P = (42, "Alice")
System.Console.Write($"{P.a} {P.b}")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub ExtensionMethodOnTuple()
Dim comp = CompileAndVerify(
<compilation>
<file name="a.vb">
Module M
<System.Runtime.CompilerServices.Extension()>
Sub Extension(x As (a As Integer, b As String))
System.Console.Write($"{x.a} {x.b}")
End Sub
End Module
Class C
Shared Sub Main()
Call (42, "Alice").Extension()
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:="42 Alice")
End Sub
<Fact>
Public Sub TupleInOptionalParam()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice"))
End Sub
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<![CDATA[
BC30059: Constant expression is required.
Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice"))
~~~~~~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub TupleDefaultInOptionalParam()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
M()
End Sub
Shared Sub M(Optional x As (a As Integer, b As String) = Nothing)
System.Console.Write($"{x.a} {x.b}")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 ]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleAsNamedParam()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
M(y:=(42, "Alice"), x:=1)
End Sub
Shared Sub M(x As Integer, y As (a As Integer, b As String))
System.Console.Write($"{y.a} {y.Item2}")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LongTupleCreationWithNames()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x =
(a:=1, b:=2, c:=3, d:=4, e:=5, f:=6, g:=7, h:="Alice", i:=2, j:=3, k:=4, l:=5, m:=6, n:=7, o:="Bob", p:=2, q:=3)
System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l} {x.m} {x.n} {x.o} {x.p} {x.q}")
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>,
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, e As System.Int32, f As System.Int32, g As System.Int32, " _
+ "h As System.String, i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32, m As System.Int32, n As System.Int32, " _
+ "o As System.String, p As System.Int32, q As System.Int32)",
model.GetTypeInfo(x).Type.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleCreationWithInferredNamesWithVB15()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Dim e As Integer = 5
Dim f As Integer = 6
Dim instance As C = Nothing
Sub M()
Dim a As Integer = 1
Dim b As Integer = 3
Dim Item4 As Integer = 4
Dim g As Integer = 7
Dim Rest As Integer = 9
Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) =
(a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest)
Dim z = (x:=b, b)
System.Console.Write(y)
System.Console.Write(z)
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15),
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)",
model.GetTypeInfo(yTuple).Type.ToTestDisplayString())
Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleCreationWithInferredNames()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Dim e As Integer = 5
Dim f As Integer = 6
Dim instance As C = Nothing
Sub M()
Dim a As Integer = 1
Dim b As Integer = 3
Dim Item4 As Integer = 4
Dim g As Integer = 7
Dim Rest As Integer = 9
Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) =
(a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest)
Dim z = (x:=b, b)
System.Console.Write(y)
System.Console.Write(z)
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3),
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)",
model.GetTypeInfo(yTuple).Type.ToTestDisplayString())
Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleCreationWithInferredNames2()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Dim e As Integer = 5
Dim instance As C = Nothing
Function M() As Integer
Dim y As (Integer?, object) = (instance?.e, (e, instance.M()))
System.Console.Write(y)
Return 42
End Function
End Class
</file>
</compilation>,
references:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3),
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(e As System.Nullable(Of System.Int32), (e As System.Int32, M As System.Int32))",
model.GetTypeInfo(yTuple).Type.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MissingMemberAccessWithVB15()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Sub M()
Dim a As Integer = 1
Dim t = (a, 2)
System.Console.Write(t.A)
System.Console.Write(GetTuple().a)
End Sub
Function GetTuple() As (Integer, Integer)
Return (1, 2)
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp.AssertTheseDiagnostics(<errors>
BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name.
System.Console.Write(t.A)
~~~
BC30456: 'a' is not a member of '(Integer, Integer)'.
System.Console.Write(GetTuple().a)
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub UseSiteDiagnosticOnTupleField()
Dim missingComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UseSiteDiagnosticOnTupleField_missingComp">
<file name="missing.vb">
Public Class Missing
End Class
</file>
</compilation>)
missingComp.VerifyDiagnostics()
Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="lib.vb">
Public Class C
Public Shared Function GetTuple() As (Missing, Integer)
Throw New System.Exception()
End Function
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, missingComp.ToMetadataReference()})
libComp.VerifyDiagnostics()
Dim source =
<compilation>
<file name="a.vb">
Class D
Sub M()
System.Console.Write(C.GetTuple().Item1)
End Sub
End Class
</file>
</compilation>
Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp15.AssertTheseDiagnostics(<errors>
BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project.
System.Console.Write(C.GetTuple().Item1)
~~~~~~~~~~~~
</errors>)
Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
comp15_3.AssertTheseDiagnostics(<errors>
BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project.
System.Console.Write(C.GetTuple().Item1)
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub UseSiteDiagnosticOnTupleField2()
Dim source =
<compilation>
<file name="a.vb">
Class C
Sub M()
Dim a = 1
Dim t = (a, 2)
System.Console.Write(t.a)
End Sub
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
</file>
</compilation>
Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp15.AssertTheseDiagnostics(<errors>
BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined.
System.Console.Write(t.a)
~~~
</errors>)
Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
comp15_3.AssertTheseDiagnostics(<errors>
BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined.
System.Console.Write(t.a)
~~~
</errors>)
End Sub
<Fact>
Public Sub MissingMemberAccessWithExtensionWithVB15()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
Dim a As Integer = 1
Dim t = (a, 2)
System.Console.Write(t.A)
System.Console.Write(GetTuple().a)
End Sub
Function GetTuple() As (Integer, Integer)
Return (1, 2)
End Function
End Class
Module Extensions
<System.Runtime.CompilerServices.Extension()>
Public Function A(self As (Integer, Action)) As String
Return Nothing
End Function
End Module
</file>
</compilation>,
additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp.AssertTheseDiagnostics(<errors>
BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name.
System.Console.Write(t.A)
~~~
BC30456: 'a' is not a member of '(Integer, Integer)'.
System.Console.Write(GetTuple().a)
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub MissingMemberAccessWithVB15_3()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Sub M()
Dim a As Integer = 1
Dim t = (a, 2)
System.Console.Write(t.b)
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
comp.AssertTheseDiagnostics(<errors>
BC30456: 'b' is not a member of '(a As Integer, Integer)'.
System.Console.Write(t.b)
~~~
</errors>)
End Sub
<Fact>
Public Sub InferredNamesInLinq()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Linq
Class C
Dim f1 As Integer = 0
Dim f2 As Integer = 1
Shared Sub Main(list As IEnumerable(Of C))
Dim result = list.Select(Function(c) (c.f1, c.f2)).Where(Function(t) t.f2 = 1) ' t and result have names f1 and f2
System.Console.Write(result.Count())
End Sub
End Class
</file>
</compilation>,
references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3),
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Dim result = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0)
Dim resultSymbol = model.GetDeclaredSymbol(result)
Assert.Equal("result As System.Collections.Generic.IEnumerable(Of (f1 As System.Int32, f2 As System.Int32))", resultSymbol.ToTestDisplayString())
End Sub)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub InferredNamesInTernary()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim i = 1
Dim flag = False
Dim t = If(flag, (i, 2), (i, 3))
System.Console.Write(t.i)
End Sub
End Class
</file>
</compilation>,
references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3),
expectedOutput:="1")
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub InferredNames_ExtensionNowFailsInVB15ButNotVB15_3()
Dim source = <compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Dim M As Action = Sub() Console.Write("lambda")
Dim t = (1, M)
t.M()
End Sub
End Class
Module Extensions
<System.Runtime.CompilerServices.Extension()>
Public Sub M(self As (Integer, Action))
Console.Write("extension")
End Sub
End Module
</file>
</compilation>
' When VB 15 shipped, no tuple element would be found/inferred, so the extension method was called.
' The VB 15.3 compiler disallows that, even when LanguageVersion is 15.
Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp15.AssertTheseDiagnostics(<errors>
BC37289: Tuple element name 'M' is inferred. Please use language version 15.3 or greater to access an element by its inferred name.
t.M()
~~~
</errors>)
Dim verifier15_3 = CompileAndVerify(source,
references:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3),
expectedOutput:="lambda")
verifier15_3.VerifyDiagnostics()
End Sub
<Fact>
Public Sub InferredName_Conversion()
Dim source = <compilation>
<file>
Class C
Shared Sub F(t As (Object, Object))
End Sub
Shared Sub G(o As Object)
Dim t = (1, o)
F(t)
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef},
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
comp.AssertTheseEmitDiagnostics(<errors/>)
End Sub
<Fact>
Public Sub LongTupleWithArgumentEvaluation()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x = (a:=PrintAndReturn(1), b:=2, c:=3, d:=PrintAndReturn(4), e:=5, f:=6, g:=PrintAndReturn(7), h:=PrintAndReturn("Alice"), i:=2, j:=3, k:=4, l:=5, m:=6, n:=PrintAndReturn(7), o:=PrintAndReturn("Bob"), p:=2, q:=PrintAndReturn(3))
End Sub
Shared Function PrintAndReturn(Of T)(i As T)
System.Console.Write($"{i} ")
Return i
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 4 7 Alice 7 Bob 3]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DuplicateTupleMethodsNotAllowed()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Function M(a As (String, String)) As (Integer, Integer)
Return new System.ValueTuple(Of Integer, Integer)(a.Item1.Length, a.Item2.Length)
End Function
Function M(a As System.ValueTuple(Of String, String)) As System.ValueTuple(Of Integer, Integer)
Return (a.Item1.Length, a.Item2.Length)
End Function
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30269: 'Public Function M(a As (String, String)) As (Integer, Integer)' has multiple definitions with identical signatures.
Function M(a As (String, String)) As (Integer, Integer)
~
</errors>)
End Sub
<Fact>
Public Sub TupleArrays()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Interface I
Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)()
End Interface
Class C
Implements I
Shared Sub Main()
Dim i As I = new C()
Dim r = i.M(new System.ValueTuple(Of Integer, Integer)() { new System.ValueTuple(Of Integer, Integer)(1, 2) })
System.Console.Write($"{r(0).Item1} {r(0).Item2}")
End Sub
Public Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)() Implements I.M
Return New System.ValueTuple(Of Integer, Integer)() { (a(0).Item1, a(0).Item2) }
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleRef()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim r = (1, 2)
M(r)
System.Console.Write($"{r.Item1} {r.Item2}")
End Sub
Shared Sub M(ByRef a As (Integer, Integer))
System.Console.WriteLine($"{a.Item1} {a.Item2}")
a = (3, 4)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2
3 4]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleOut()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim r As (Integer, Integer)
M(r)
System.Console.Write($"{r.Item1} {r.Item2}")
End Sub
Shared Sub M(ByRef a As (Integer, Integer))
System.Console.WriteLine($"{a.Item1} {a.Item2}")
a = (1, 2)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 0
1 2]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleTypeArgs()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim a = (1, "Alice")
Dim r = M(Of Integer, String)(a)
System.Console.Write($"{r.Item1} {r.Item2}")
End Sub
Shared Function M(Of T1, T2)(a As (T1, T2)) As (T1, T2)
Return a
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 Alice]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub NullableTuple()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
M((1, "Alice"))
End Sub
Shared Sub M(a As (Integer, String)?)
System.Console.Write($"{a.HasValue} {a.Value.Item1} {a.Value.Item2}")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[True 1 Alice]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleUnsupportedInUsingStatement()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports VT2 = (Integer, Integer)
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC30203: Identifier expected.
Imports VT2 = (Integer, Integer)
~
BC40056: Namespace or type specified in the Imports '' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports VT2 = (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC32093: 'Of' required when specifying type arguments for a generic type or method.
Imports VT2 = (Integer, Integer)
~
</errors>)
End Sub
<Fact>
Public Sub MissingTypeInAlias()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports VT2 = System.ValueTuple(Of Integer, Integer) ' ValueTuple is referenced but does not exist
Namespace System
Public Class Bogus
End Class
End Namespace
Namespace TuplesCrash2
Class C
Shared Sub Main()
End Sub
End Class
End Namespace
]]></file>
</compilation>)
Dim tree = comp.SyntaxTrees.First()
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = model.LookupStaticMembers(234)
For i As Integer = 0 To tree.GetText().Length
model.LookupStaticMembers(i)
Next
' Didn't crash
End Sub
<Fact>
Public Sub MultipleDefinitionsOfValueTuple()
Dim source1 =
<compilation>
<file name="a.vb">
Public Module M1
<System.Runtime.CompilerServices.Extension()>
Public Sub Extension(x As Integer, y As (Integer, Integer))
System.Console.Write("M1.Extension")
End Sub
End Module
<%= s_trivial2uple %></file>
</compilation>
Dim source2 =
<compilation>
<file name="a.vb">
Public Module M2
<System.Runtime.CompilerServices.Extension()>
Public Sub Extension(x As Integer, y As (Integer, Integer))
System.Console.Write("M2.Extension")
End Sub
End Module
<%= s_trivial2uple %></file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(source1, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp1")
comp1.AssertNoDiagnostics()
Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp2")
comp2.AssertNoDiagnostics()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports M1
Imports M2
Class C
Public Shared Sub Main()
Dim x As Integer = 0
x.Extension((1, 1))
End Sub
End Class
</file>
</compilation>
Dim comp3 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={comp1.ToMetadataReference(), comp2.ToMetadataReference()})
comp3.AssertTheseDiagnostics(
<errors>
BC30521: Overload resolution failed because no accessible 'Extension' is most specific for these arguments:
Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M1': Not most specific.
Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M2': Not most specific.
x.Extension((1, 1))
~~~~~~~~~
BC37305: Predefined type 'ValueTuple(Of ,)' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
x.Extension((1, 1))
~~~~~~
</errors>)
Dim comp4 = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={comp1.ToMetadataReference()},
options:=TestOptions.DebugExe)
comp4.AssertTheseDiagnostics(
<errors>
BC40056: Namespace or type specified in the Imports 'M2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports M2
~~
</errors>)
CompileAndVerify(comp4, expectedOutput:=<![CDATA[M1.Extension]]>)
End Sub
<Fact>
Public Sub Tuple2To8Members()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System.Console
Class C
Shared Sub Main()
Write((1, 2).Item1)
Write((1, 2).Item2)
WriteLine()
Write((1, 2, 3).Item1)
Write((1, 2, 3).Item2)
Write((1, 2, 3).Item3)
WriteLine()
Write((1, 2, 3, 4).Item1)
Write((1, 2, 3, 4).Item2)
Write((1, 2, 3, 4).Item3)
Write((1, 2, 3, 4).Item4)
WriteLine()
Write((1, 2, 3, 4, 5).Item1)
Write((1, 2, 3, 4, 5).Item2)
Write((1, 2, 3, 4, 5).Item3)
Write((1, 2, 3, 4, 5).Item4)
Write((1, 2, 3, 4, 5).Item5)
WriteLine()
Write((1, 2, 3, 4, 5, 6).Item1)
Write((1, 2, 3, 4, 5, 6).Item2)
Write((1, 2, 3, 4, 5, 6).Item3)
Write((1, 2, 3, 4, 5, 6).Item4)
Write((1, 2, 3, 4, 5, 6).Item5)
Write((1, 2, 3, 4, 5, 6).Item6)
WriteLine()
Write((1, 2, 3, 4, 5, 6, 7).Item1)
Write((1, 2, 3, 4, 5, 6, 7).Item2)
Write((1, 2, 3, 4, 5, 6, 7).Item3)
Write((1, 2, 3, 4, 5, 6, 7).Item4)
Write((1, 2, 3, 4, 5, 6, 7).Item5)
Write((1, 2, 3, 4, 5, 6, 7).Item6)
Write((1, 2, 3, 4, 5, 6, 7).Item7)
WriteLine()
Write((1, 2, 3, 4, 5, 6, 7, 8).Item1)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item2)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item3)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item4)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item5)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item6)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item7)
Write((1, 2, 3, 4, 5, 6, 7, 8).Item8)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[12
123
1234
12345
123456
1234567
12345678]]>)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_BadArguments()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(underlyingType:=Nothing, elementNames:=Nothing))
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType)
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item1")))
Assert.Contains(CodeAnalysisResources.TupleElementNameCountMismatch, ex.Message)
Dim tree = VisualBasicSyntaxTree.ParseText("Class C")
Dim loc1 = Location.Create(tree, New TextSpan(0, 1))
ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, elementLocations:=ImmutableArray.Create(loc1)))
Assert.Contains(CodeAnalysisResources.TupleElementLocationCountMismatch, ex.Message)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_WithValueTuple()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create(Of String)(Nothing, Nothing))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault)
Assert.Equal((New String() {"System.Int32", "System.String"}), ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
Private Shared Function ElementTypeNames(tuple As INamedTypeSymbol) As IEnumerable(Of String)
Return tuple.TupleElements.Select(Function(t) t.Type.ToTestDisplayString())
End Function
<Fact>
Public Sub CreateTupleTypeSymbol_Locations()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType)
Dim tree = VisualBasicSyntaxTree.ParseText("Class C")
Dim loc1 = Location.Create(tree, New TextSpan(0, 1))
Dim loc2 = Location.Create(tree, New TextSpan(1, 1))
Dim tuple = comp.CreateTupleTypeSymbol(
vt2, ImmutableArray.Create("i1", "i2"), ImmutableArray.Create(loc1, loc2))
Assert.True(tuple.IsTupleType)
Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind)
Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString())
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple))
Assert.Equal(SymbolKind.NamedType, tuple.Kind)
Assert.Equal(loc1, tuple.GetMembers("i1").Single.Locations.Single())
Assert.Equal(loc2, tuple.GetMembers("i2").Single.Locations.Single())
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing)
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob"))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames))
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_WithSomeNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, stringType, intType)
Dim tupleWithSomeNames = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create(Nothing, "Item2", "Charlie"))
Assert.True(tupleWithSomeNames.IsTupleType)
Assert.Equal(SymbolKind.ErrorType, tupleWithSomeNames.TupleUnderlyingType.Kind)
Assert.Equal("(System.Int32, Item2 As System.String, Charlie As System.Int32)", tupleWithSomeNames.ToTestDisplayString())
Assert.Equal(New String() {Nothing, "Item2", "Charlie"}, GetTupleElementNames(tupleWithSomeNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tupleWithSomeNames))
Assert.Equal(SymbolKind.NamedType, tupleWithSomeNames.Kind)
Assert.All(tupleWithSomeNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_WithBadNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item2", "Item1"))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString())
Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames))
Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_Tuple8NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).
Construct(intType, stringType, intType, stringType, intType, stringType, intType,
comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType))
Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, Nothing)
Assert.True(tuple8WithoutNames.IsTupleType)
Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)",
tuple8WithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"},
ElementTypeNames(tuple8WithoutNames))
Assert.All(tuple8WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_Tuple8WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).
Construct(intType, stringType, intType, stringType, intType, stringType, intType,
comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType))
Dim tuple8WithNames = comp.CreateTupleTypeSymbol(vt8, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"))
Assert.True(tuple8WithNames.IsTupleType)
Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)",
tuple8WithNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"},
ElementTypeNames(tuple8WithNames))
Assert.All(tuple8WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_Tuple9NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).
Construct(intType, stringType, intType, stringType, intType, stringType, intType,
comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType))
Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(vt9, Nothing)
Assert.True(tuple9WithoutNames.IsTupleType)
Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)",
tuple9WithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"},
ElementTypeNames(tuple9WithoutNames))
Assert.All(tuple9WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_Tuple9WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).
Construct(intType, stringType, intType, stringType, intType, stringType, intType,
comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType))
Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"))
Assert.True(tuple9WithNames.IsTupleType)
Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)",
tuple9WithNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"},
ElementTypeNames(tuple9WithNames))
Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_Tuple9WithDefaultNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).
Construct(intType, stringType, intType, stringType, intType, stringType, intType,
comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType))
Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"))
Assert.True(tuple9WithNames.IsTupleType)
Assert.Equal("(Item1 As System.Int32, Item2 As System.String, Item3 As System.Int32, Item4 As System.String, Item5 As System.Int32, Item6 As System.String, Item7 As System.Int32, Item8 As System.String, Item9 As System.Int32)",
tuple9WithNames.ToTestDisplayString())
Assert.Equal(New String() {"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"}, GetTupleElementNames(tuple9WithNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"},
ElementTypeNames(tuple9WithNames))
Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_ElementTypeIsError()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, ErrorTypeSymbol.UnknownResultType)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing)
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type)
Assert.Equal(2, types.Length)
Assert.Equal(SymbolKind.NamedType, types(0).Kind)
Assert.Equal(SymbolKind.ErrorType, types(1).Kind)
Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()),
Sub(Loc) Assert.Equal(Loc, Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_BadNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType)
Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, intType, intType)
' Illegal VB identifier, space and null
Dim tuple2 = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create("123", " ", Nothing))
Assert.Equal({"123", " ", Nothing}, GetTupleElementNames(tuple2))
' Reserved keywords
Dim tuple3 = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("return", "class"))
Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3))
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=intType))
Assert.Contains(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, ex.Message)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_EmptyNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType)
' Illegal VB identifier and empty
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("123", "")))
Assert.Contains(CodeAnalysisResources.TupleElementNameEmpty, ex.Message)
Assert.Contains("1", ex.Message)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_CSharpElements()
Dim csSource = "public class C { }"
Dim csComp = CreateCSharpCompilation("CSharp", csSource,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csComp.VerifyDiagnostics()
Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(csType, Nothing))
Assert.Contains(VBResources.NotAVbSymbol, ex.Message)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_BadArguments()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=Nothing, elementNames:=Nothing))
' 0-tuple and 1-tuple are not supported at this point
Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray(Of ITypeSymbol).Empty, elementNames:=Nothing))
Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType), elementNames:=Nothing))
' If names are provided, you need as many as element types
Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, intType), elementNames:=ImmutableArray.Create("Item1")))
' null types aren't allowed
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, Nothing), elementNames:=Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_WithValueTuple()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create(Of String)(Nothing, Nothing))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_Locations()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tree = VisualBasicSyntaxTree.ParseText("Class C")
Dim loc1 = Location.Create(tree, New TextSpan(0, 1))
Dim loc2 = Location.Create(tree, New TextSpan(1, 1))
Dim tuple = comp.CreateTupleTypeSymbol(
ImmutableArray.Create(intType, stringType),
ImmutableArray.Create("i1", "i2"),
ImmutableArray.Create(loc1, loc2))
Assert.True(tuple.IsTupleType)
Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind)
Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString())
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple))
Assert.Equal(SymbolKind.NamedType, tuple.Kind)
Assert.Equal(loc1, tuple.GetMembers("i1").Single().Locations.Single())
Assert.Equal(loc2, tuple.GetMembers("i2").Single().Locations.Single())
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), Nothing)
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("Alice", "Bob"))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind)
Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames))
Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_WithBadNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("Item2", "Item1"))
Assert.True(tupleWithoutNames.IsTupleType)
Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString())
Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames))
Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames))
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_Tuple8NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType),
Nothing)
Assert.True(tuple8WithoutNames.IsTupleType)
Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)",
tuple8WithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"},
ElementTypeNames(tuple8WithoutNames))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_Tuple8WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tuple8WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType),
ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"))
Assert.True(tuple8WithNames.IsTupleType)
Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)",
tuple8WithNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"},
ElementTypeNames(tuple8WithNames))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_Tuple9NoNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType),
Nothing)
Assert.True(tuple9WithoutNames.IsTupleType)
Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)",
tuple9WithoutNames.ToTestDisplayString())
Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault)
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"},
ElementTypeNames(tuple9WithoutNames))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_Tuple9WithNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Dim tuple9WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType),
ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"))
Assert.True(tuple9WithNames.IsTupleType)
Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)",
tuple9WithNames.ToTestDisplayString())
Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames))
Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"},
ElementTypeNames(tuple9WithNames))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_ElementTypeIsError()
Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><%= s_trivial2uple %></file>
</compilation>)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()})
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, ErrorTypeSymbol.UnknownResultType), Nothing)
Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind)
Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type)
Assert.Equal(2, types.Length)
Assert.Equal(SymbolKind.NamedType, types(0).Kind)
Assert.Equal(SymbolKind.ErrorType, types(1).Kind)
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol2_BadNames()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
' Illegal VB identifier and blank
Dim tuple2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("123", " "))
Assert.Equal({"123", " "}, GetTupleElementNames(tuple2))
' Reserved keywords
Dim tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("return", "class"))
Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3))
End Sub
Private Shared Function GetTupleElementNames(tuple As INamedTypeSymbol) As ImmutableArray(Of String)
Dim elements = tuple.TupleElements
If elements.All(Function(e) e.IsImplicitlyDeclared) Then
Return Nothing
End If
Return elements.SelectAsArray(Function(e) e.ProvidedTupleElementNameOrNull)
End Function
<Fact>
Public Sub CreateTupleTypeSymbol2_CSharpElements()
Dim csSource = "public class C { }"
Dim csComp = CreateCSharpCompilation("CSharp", csSource,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csComp.VerifyDiagnostics()
Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol)
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(ImmutableArray.Create(stringType, csType), Nothing))
End Sub
<Fact>
Public Sub CreateTupleTypeSymbol_ComparingSymbols()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Dim F As System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (a As String, b As String))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
Dim tuple1 = comp.GlobalNamespace.GetMember(Of SourceMemberFieldSymbol)("C.F").Type
Dim intType = comp.GetSpecialType(SpecialType.System_Int32)
Dim stringType = comp.GetSpecialType(SpecialType.System_String)
Dim twoStrings = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, stringType)
Dim twoStringsWithNames = DirectCast(comp.CreateTupleTypeSymbol(twoStrings, ImmutableArray.Create("a", "b")), TypeSymbol)
Dim tuple2Underlying = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).Construct(intType, intType, intType, intType, intType, intType, intType, twoStringsWithNames)
Dim tuple2 = DirectCast(comp.CreateTupleTypeSymbol(tuple2Underlying), TypeSymbol)
Dim tuple3 = DirectCast(comp.CreateTupleTypeSymbol(ImmutableArray.Create(Of ITypeSymbol)(intType, intType, intType, intType, intType, intType, intType, stringType, stringType),
ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol)
Dim tuple4 = DirectCast(comp.CreateTupleTypeSymbol(CType(tuple1.TupleUnderlyingType, INamedTypeSymbol),
ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol)
Assert.True(tuple1.Equals(tuple2))
'Assert.True(tuple1.Equals(tuple2, TypeCompareKind.IgnoreDynamicAndTupleNames))
Assert.False(tuple1.Equals(tuple3))
'Assert.True(tuple1.Equals(tuple3, TypeCompareKind.IgnoreDynamicAndTupleNames))
Assert.False(tuple1.Equals(tuple4))
'Assert.True(tuple1.Equals(tuple4, TypeCompareKind.IgnoreDynamicAndTupleNames))
End Sub
<Fact>
Public Sub TupleMethodsOnNonTupleType()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef})
Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_String)
Assert.False(intType.IsTupleType)
Assert.True(intType.TupleElementNames.IsDefault)
Assert.True(intType.TupleElementTypes.IsDefault)
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_UnderlyingType_DefaultArgs()
Dim comp = CreateCompilation(
"Module Program
Private F As (Integer, String)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim underlyingType = tuple1.TupleUnderlyingType
Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames:=Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_ElementTypes_DefaultArgs()
Dim comp = CreateCompilation(
"Module Program
Private F As (Integer, String)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type)
Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing, Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames:=Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_01()
Dim comp = CreateCompilation(
"Module Program
Private F As (Integer, String)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim underlyingType = tuple1.TupleUnderlyingType
Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty))
Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message)
tuple2 = comp.CreateTupleTypeSymbol(
underlyingType,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(
underlyingType,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(
underlyingType,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_02()
Dim comp = CreateCompilation(
"Module Program
Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim underlyingType = tuple1.TupleUnderlyingType
Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing)
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8)))
Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message)
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9))
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9))
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_01()
Dim comp = CreateCompilation(
"Module Program
Private F As (Integer, String)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type)
Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing)
Assert.True(tuple1.Equals(tuple2))
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty))
Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message)
tuple2 = comp.CreateTupleTypeSymbol(
elementTypes,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(
elementTypes,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(
elementTypes,
elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None))
Assert.True(tuple1.Equals(tuple2))
Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")>
Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_02()
Dim comp = CreateCompilation(
"Module Program
Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object)
End Module")
Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol)
Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type)
Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing)
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8)))
Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message)
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9))
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9))
Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString())
End Sub
Private Shared Function CreateAnnotations(annotation As CodeAnalysis.NullableAnnotation, n As Integer) As ImmutableArray(Of CodeAnalysis.NullableAnnotation)
Return ImmutableArray.CreateRange(Enumerable.Range(0, n).Select(Function(i) annotation))
End Function
Private Shared Function TypeEquals(a As ITypeSymbol, b As ITypeSymbol, compareKind As TypeCompareKind) As Boolean
Return TypeSymbol.Equals(DirectCast(a, TypeSymbol), DirectCast(b, TypeSymbol), compareKind)
End Function
<Fact>
Public Sub TupleTargetTypeAndConvert01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
' This works
Dim x1 As (Short, String) = (1, "hello")
Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String))
Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String))
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from '(Long, String)' to '(Short, String)'.
Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As String)' to '(a As Short, b As String)'.
Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleTargetTypeAndConvert02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x2 As (Short, String) = DirectCast((1, "hello"), (Byte, String))
System.Console.WriteLine(x2)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello)]]>)
verifier.VerifyDiagnostics()
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 41 (0x29)
.maxstack 3
.locals init (System.ValueTuple(Of Byte, String) V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldstr "hello"
IL_0008: call "Sub System.ValueTuple(Of Byte, String)..ctor(Byte, String)"
IL_000d: ldloc.0
IL_000e: ldfld "System.ValueTuple(Of Byte, String).Item1 As Byte"
IL_0013: ldloc.0
IL_0014: ldfld "System.ValueTuple(Of Byte, String).Item2 As String"
IL_0019: newobj "Sub System.ValueTuple(Of Short, String)..ctor(Short, String)"
IL_001e: box "System.ValueTuple(Of Short, String)"
IL_0023: call "Sub System.Console.WriteLine(Object)"
IL_0028: ret
}
]]>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As (Integer, Integer)
x = (Nothing, Nothing, Nothing)
x = (1, 2, 3)
x = (1, "string")
x = (1, 1, garbage)
x = (1, 1, )
x = (Nothing, Nothing) ' ok
x = (1, Nothing) ' ok
x = (1, Function(t) t)
x = Nothing ' ok
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'.
x = (Nothing, Nothing, Nothing)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'.
x = (1, 2, 3)
~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.
x = (1, "string")
~~~~~~~~
BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level.
x = (1, 1, garbage)
~~~~~~~
BC30201: Expression expected.
x = (1, 1, )
~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
x = (1, Function(t) t)
~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleExplicitConversionFail01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As (Integer, Integer)
x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer))
x = DirectCast((1, 2, 3), (Integer, Integer))
x = DirectCast((1, "string"), (Integer, Integer)) ' ok
x = DirectCast((1, 1, garbage), (Integer, Integer))
x = DirectCast((1, 1, ), (Integer, Integer))
x = DirectCast((Nothing, Nothing), (Integer, Integer)) ' ok
x = DirectCast((1, Nothing), (Integer, Integer)) ' ok
x = DirectCast((1, Function(t) t), (Integer, Integer))
x = DirectCast(Nothing, (Integer, Integer)) ' ok
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'.
x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'.
x = DirectCast((1, 2, 3), (Integer, Integer))
~~~~~~~~~
BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level.
x = DirectCast((1, 1, garbage), (Integer, Integer))
~~~~~~~
BC30201: Expression expected.
x = DirectCast((1, 1, ), (Integer, Integer))
~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
x = DirectCast((1, Function(t) t), (Integer, Integer))
~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As System.ValueTuple(Of Integer, Integer)
x = (Nothing, Nothing, Nothing)
x = (1, 2, 3)
x = (1, "string")
x = (1, 1, garbage)
x = (1, 1, )
x = (Nothing, Nothing) ' ok
x = (1, Nothing) ' ok
x = (1, Function(t) t)
x = Nothing ' ok
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'.
x = (Nothing, Nothing, Nothing)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'.
x = (1, 2, 3)
~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.
x = (1, "string")
~~~~~~~~
BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level.
x = (1, 1, garbage)
~~~~~~~
BC30201: Expression expected.
x = (1, 1, )
~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
x = (1, Function(t) t)
~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleInferredLambdaStrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim valid = (1, Function() Nothing)
Dim x = (Nothing, Function(t) t)
Dim y = (1, Function(t) t)
Dim z = (Function(t) t, Function(t) t)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
Dim x = (Nothing, Function(t) t)
~
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
Dim y = (1, Function(t) t)
~
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
Dim z = (Function(t) t, Function(t) t)
~
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
Dim z = (Function(t) t, Function(t) t)
~
</errors>)
End Sub
<Fact()>
Public Sub TupleInferredLambdaStrictOff()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Class C
Shared Sub Main()
Dim valid = (1, Function() Nothing)
Test(valid)
Dim x = (Nothing, Function(t) t)
Test(x)
Dim y = (1, Function(t) t)
Test(y)
End Sub
shared function Test(of T)(x as T) as T
System.Console.WriteLine(GetType(T))
return x
End Function
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_0`1[System.Object]]
System.ValueTuple`2[System.Object,VB$AnonymousDelegate_1`2[System.Object,System.Object]]
System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_1`2[System.Object,System.Object]]
]]>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As (String, String)
x = (Nothing, Nothing, Nothing)
x = (1, 2, 3)
x = (1, "string")
x = (1, 1, garbage)
x = (1, 1, )
x = (Nothing, Nothing) ' ok
x = (1, Nothing) ' ok
x = (1, Function(t) t)
x = Nothing ' ok
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(String, String)'.
x = (Nothing, Nothing, Nothing)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(String, String)'.
x = (1, 2, 3)
~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
x = (1, "string")
~
BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level.
x = (1, 1, garbage)
~~~~~~~
BC30201: Expression expected.
x = (1, 1, )
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
x = (1, Nothing) ' ok
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
x = (1, Function(t) t)
~
BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
x = (1, Function(t) t)
~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As ((Integer, Integer), Integer)
x = ((Nothing, Nothing, Nothing), 1)
x = ((1, 2, 3), 1)
x = ((1, "string"), 1)
x = ((1, 1, garbage), 1)
x = ((1, 1, ), 1)
x = ((Nothing, Nothing), 1) ' ok
x = ((1, Nothing), 1) ' ok
x = ((1, Function(t) t), 1)
x = (Nothing, 1) ' ok
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'.
x = ((Nothing, Nothing, Nothing), 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'.
x = ((1, 2, 3), 1)
~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.
x = ((1, "string"), 1)
~~~~~~~~
BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level.
x = ((1, 1, garbage), 1)
~~~~~~~
BC30201: Expression expected.
x = ((1, 1, ), 1)
~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
x = ((1, Function(t) t), 1)
~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Shared Sub Main()
Dim x As (x0 As System.ValueTuple(Of Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)
x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
x = ((0, 0.0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 )
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9.1, 10)
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8,
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9
x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10)
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9)
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10)
End Sub
End Class
]]><%= s_trivial2uple %><%= s_trivialRemainingTuples %></file>
</compilation>)
' Intentionally not including 3-tuple for use-site errors
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type 'Integer' cannot be converted to '(Integer, Integer)'.
x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
~
BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 )
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30452: Operator '=' is not defined for types '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)' and '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30198: ')' expected.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9
~
BC30198: ')' expected.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9
~
BC30451: 'oops' is not declared. It may be inaccessible due to its protection level.
x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10)
~~~~
BC30451: 'oopsss' is not declared. It may be inaccessible due to its protection level.
x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10)
~~~~~~
BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to 'Integer'.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10)
~~~~~~~~~
BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported.
x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10)
~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleImplicitConversionFail06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim l As Func(Of String) = Function() 1
Dim x As (String, Func(Of String)) = (Nothing, Function() 1)
Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1)
Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1))
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim l As Func(Of String) = Function() 1
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim x As (String, Func(Of String)) = (Nothing, Function() 1)
~
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'.
Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1)
~~~
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'.
Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1))
~~~
</errors>)
End Sub
<Fact>
Public Sub TupleExplicitConversionFail06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim l As Func(Of String) = Function() 1
Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String)))
Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String)))
Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String))))
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim l As Func(Of String) = Function() 1
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String)))
~
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'.
Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String)))
~~~
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'.
Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String))))
~~~
</errors>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TupleCTypeNullableConversionWithTypelessTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim x As (Integer, String)? = CType((1, Nothing), (Integer, String)?)
Console.Write(x)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertNoDiagnostics()
CompileAndVerify(comp, expectedOutput:="(1, )")
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Dim [ctype] = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single()
Assert.Equal("CType((1, Nothing), (Integer, String)?)", [ctype].ToString())
comp.VerifyOperationTree([ctype], expectedOperationTree:=
<![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of (System.Int32, System.String))) (Syntax: 'CType((1, N ... , String)?)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.String)) (Syntax: '(1, Nothing)')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
]]>.Value)
End Sub
<Fact>
Public Sub TupleDirectCastNullableConversionWithTypelessTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim x As (Integer, String)? = DirectCast((1, Nothing), (Integer, String)?)
Console.Write(x)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertNoDiagnostics()
CompileAndVerify(comp, expectedOutput:="(1, )")
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleTryCastNullableConversionWithTypelessTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?)
Console.Write(x)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30792: 'TryCast' operand must be reference type, but '(Integer, String)?' is a value type.
Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?)
~~~~~~~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleTryCastNullableConversionWithTypelessTuple2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub M(Of T)()
Dim x = TryCast((0, Nothing), C(Of Integer, T))
Console.Write(x)
End Sub
End Class
Class C(Of T, U)
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(Integer, Object)' cannot be converted to 'C(Of Integer, T)'.
Dim x = TryCast((0, Nothing), C(Of Integer, T))
~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(0, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleImplicitNullableConversionWithTypelessTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Shared Sub Main()
Dim x As (Integer, String)? = (1, Nothing)
System.Console.Write(x)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertNoDiagnostics()
CompileAndVerify(comp, expectedOutput:="(1, )")
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
End Sub
<Fact>
Public Sub ImplicitConversionOnTypelessTupleWithUserConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Structure C
Shared Sub Main()
Dim x As C = (1, Nothing)
Dim y As C? = (2, Nothing)
End Sub
Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C
Return New C()
End Operator
End Structure
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
Dim y As C? = (2, Nothing)
~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(1, Nothing)", firstTuple.ToString())
Assert.Null(model.GetTypeInfo(firstTuple).Type)
Assert.Equal("C", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(firstTuple).Kind)
Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(2, Nothing)", secondTuple.ToString())
Assert.Null(model.GetTypeInfo(secondTuple).Type)
Assert.Equal("System.Nullable(Of C)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(secondTuple).Kind)
End Sub
<Fact>
Public Sub DirectCastOnTypelessTupleWithUserConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Structure C
Shared Sub Main()
Dim x = DirectCast((1, Nothing), C)
Dim y = DirectCast((2, Nothing), C?)
End Sub
Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C
Return New C()
End Operator
End Structure
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(Integer, Object)' cannot be converted to 'C'.
Dim x = DirectCast((1, Nothing), C)
~~~~~~~~~~~~
BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
Dim y = DirectCast((2, Nothing), C?)
~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(1, Nothing)", firstTuple.ToString())
Assert.Null(model.GetTypeInfo(firstTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(2, Nothing)", secondTuple.ToString())
Assert.Null(model.GetTypeInfo(secondTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
End Sub
<Fact>
Public Sub TryCastOnTypelessTupleWithUserConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Structure C
Shared Sub Main()
Dim x = TryCast((1, Nothing), C)
Dim y = TryCast((2, Nothing), C?)
End Sub
Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C
Return New C()
End Operator
End Structure
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30792: 'TryCast' operand must be reference type, but 'C' is a value type.
Dim x = TryCast((1, Nothing), C)
~
BC30792: 'TryCast' operand must be reference type, but 'C?' is a value type.
Dim y = TryCast((2, Nothing), C?)
~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(1, Nothing)", firstTuple.ToString())
Assert.Null(model.GetTypeInfo(firstTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(2, Nothing)", secondTuple.ToString())
Assert.Null(model.GetTypeInfo(secondTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
End Sub
<Fact>
Public Sub CTypeOnTypelessTupleWithUserConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Structure C
Shared Sub Main()
Dim x = CType((1, Nothing), C)
Dim y = CType((2, Nothing), C?)
End Sub
Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C
Return New C()
End Operator
End Structure
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
Dim y = CType((2, Nothing), C?)
~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(1, Nothing)", firstTuple.ToString())
Assert.Null(model.GetTypeInfo(firstTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(2, Nothing)", secondTuple.ToString())
Assert.Null(model.GetTypeInfo(secondTuple).Type)
Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
End Sub
<Fact>
Public Sub TupleTargetTypeLambda()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C
Shared Sub Test(d As Func(Of Func(Of (Short, Short))))
Console.WriteLine("short")
End Sub
Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))
Console.WriteLine("byte")
End Sub
Shared Sub Main()
Test(Function() Function() DirectCast((1, 1), (Byte, Byte)))
Test(Function() Function() (1, 1))
End Sub
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments:
'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific.
'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific.
Test(Function() Function() DirectCast((1, 1), (Byte, Byte)))
~~~~
BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments:
'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific.
'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific.
Test(Function() Function() (1, 1))
~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleTargetTypeLambda1()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C
Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))
Console.WriteLine("short")
End Sub
Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))
Console.WriteLine("byte")
End Sub
Shared Sub Main()
Test(Function() (Function() CType(1, Byte), 1))
Test(Function() (Function() 1, 1))
End Sub
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments:
'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific.
'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific.
Test(Function() (Function() CType(1, Byte), 1))
~~~~
BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments:
'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific.
'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific.
Test(Function() (Function() 1, 1))
~~~~
</errors>)
End Sub
<Fact>
Public Sub TargetTypingOverload01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Test((Nothing, Nothing))
Test((1, 1))
Test((Function() 7, Function() 8), 2)
End Sub
Shared Sub Test(Of T)(x As (T, T))
Console.WriteLine("first")
End Sub
Shared Sub Test(x As (Object, Object))
Console.WriteLine("second")
End Sub
Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T)), y As T)
Console.WriteLine("third")
Console.WriteLine(x.Item1().ToString())
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second
first
third
7]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TargetTypingOverload02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C
Shared Sub Main()
Test1((Function() 7, Function() 8))
Test2(Function() 7, Function() 8)
End Sub
Shared Sub Test1(Of T)(x As (T, T))
Console.WriteLine("first")
End Sub
Shared Sub Test1(x As (Object, Object))
Console.WriteLine("second")
End Sub
Shared Sub Test1(Of T)(x As (Func(Of T), Func(Of T)))
Console.WriteLine("third")
Console.WriteLine(x.Item1().ToString())
End Sub
Shared Sub Test2(Of T)(x As T, y as T)
Console.WriteLine("first")
End Sub
Shared Sub Test2(x As Object, y as Object)
Console.WriteLine("second")
End Sub
Shared Sub Test2(Of T)(x As Func(Of T), y as Func(Of T))
Console.WriteLine("third")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=
"first
first")
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TargetTypingNullable01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Dim x = M1()
Test(x)
End Sub
Shared Function M1() As (a As Integer, b As Double)?
Return (1, 2)
End Function
Shared Sub Test(Of T)(arg As T)
Console.WriteLine(GetType(T))
Console.WriteLine(arg)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.Double]]
(1, 2)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TargetTypingOverload01Long()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing))
Test((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
Test((Function() 11, Function() 12, Function() 13, Function() 14, Function() 15, Function() 16, Function() 17, Function() 18, Function() 19, Function() 20))
End Sub
Shared Sub Test(Of T)(x As (T, T, T, T, T, T, T, T, T, T))
Console.WriteLine("first")
End Sub
Shared Sub Test(x As (Object, Object, Object, Object, Object, Object, Object, Object, Object, Object))
Console.WriteLine("second")
End Sub
Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T)), y As T)
Console.WriteLine("third")
Console.WriteLine(x.Item1().ToString())
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second
first
first]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")>
Public Sub TargetTypingNullable02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Dim x = M1()
Test(x)
End Sub
Shared Function M1() As (a As Integer, b As String)?
Return (1, Nothing)
End Function
Shared Sub Test(Of T)(arg As T)
Console.WriteLine(GetType(T))
Console.WriteLine(arg)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]]
(1, )]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")>
Public Sub TargetTypingNullable02Long()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Dim x = M1()
Console.WriteLine(x?.a)
Console.WriteLine(x?.a8)
Test(x)
End Sub
Shared Function M1() As (a As Integer, b As String, a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, a8 As Integer)?
Return (1, Nothing, 1, 2, 3, 4, 5, 6, 7, 8)
End Function
Shared Sub Test(Of T)(arg As T)
Console.WriteLine(arg)
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]]
(1, )]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")>
Public Sub TargetTypingNullableOverload()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)) ' Overload resolution fails
Test(("a", "a", "a", "a", "a", "a", "a", "a", "a", "a"))
Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
End Sub
Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String))
Console.WriteLine("first")
End Sub
Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String)?)
Console.WriteLine("second")
End Sub
Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)?)
Console.WriteLine("third")
End Sub
Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer))
Console.WriteLine("fourth")
End Sub
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[first
fourth]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact()>
<WorkItem(13277, "https://github.com/dotnet/roslyn/issues/13277")>
<WorkItem(14365, "https://github.com/dotnet/roslyn/issues/14365")>
Public Sub CreateTupleTypeSymbol_UnderlyingTypeIsError()
Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, TestReferences.SymbolsTests.netModule.netModule1})
Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32)
Dim vt2 = comp.CreateErrorTypeSymbol(Nothing, "ValueTuple", 2).Construct(intType, intType)
Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=vt2))
Dim csComp = CreateCSharpCompilation("")
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorTypeSymbol(Nothing, Nothing, 2))
Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(Nothing, "a", -1))
Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(csComp.GlobalNamespace, "a", 1))
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(Nothing, "a"))
Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, Nothing))
Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, "a"))
Dim ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a")
Assert.Equal("a", ns.ToTestDisplayString())
Assert.False(ns.IsGlobalNamespace)
Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind)
Assert.Same(comp.GlobalNamespace, ns.ContainingSymbol)
Assert.Same(comp.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly)
Assert.Same(comp.GlobalNamespace.ContainingModule, ns.ContainingModule)
ns = comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "a")
Assert.Equal("a", ns.ToTestDisplayString())
Assert.False(ns.IsGlobalNamespace)
Assert.Equal(NamespaceKind.Assembly, ns.NamespaceKind)
Assert.Same(comp.Assembly.GlobalNamespace, ns.ContainingSymbol)
Assert.Same(comp.Assembly.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly)
Assert.Same(comp.Assembly.GlobalNamespace.ContainingModule, ns.ContainingModule)
ns = comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "a")
Assert.Equal("a", ns.ToTestDisplayString())
Assert.False(ns.IsGlobalNamespace)
Assert.Equal(NamespaceKind.Module, ns.NamespaceKind)
Assert.Same(comp.SourceModule.GlobalNamespace, ns.ContainingSymbol)
Assert.Same(comp.SourceModule.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly)
Assert.Same(comp.SourceModule.GlobalNamespace.ContainingModule, ns.ContainingModule)
ns = comp.CreateErrorNamespaceSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"), "b")
Assert.Equal("a.b", ns.ToTestDisplayString())
ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "")
Assert.Equal("", ns.ToTestDisplayString())
Assert.False(ns.IsGlobalNamespace)
vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType)
Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString())
vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType)
Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString())
vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType)
Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString())
End Sub
<Fact>
<WorkItem(13042, "https://github.com/dotnet/roslyn/issues/13042")>
Public Sub GetSymbolInfoOnTupleType()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module C
Function M() As (System.Int32, String)
throw new System.Exception()
End Function
End Module
</file>
</compilation>, references:=s_valueTupleRefs)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim type = nodes.OfType(Of QualifiedNameSyntax)().First()
Assert.Equal("System.Int32", type.ToString())
Assert.NotNull(model.GetSymbolInfo(type).Symbol)
Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString())
End Sub
<Fact(Skip:="See bug 16697")>
<WorkItem(16697, "https://github.com/dotnet/roslyn/issues/16697")>
Public Sub GetSymbolInfo_01()
Dim source = "
Class C
Shared Sub Main()
Dim x1 = (Alice:=1, ""hello"")
Dim Alice = x1.Alice
End Sub
End Class
"
Dim tree = Parse(source, options:=TestOptions.Regular)
Dim comp = CreateCompilationWithMscorlib40(tree)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim nc = nodes.OfType(Of NameColonEqualsSyntax)().ElementAt(0)
Dim sym = model.GetSymbolInfo(nc.Name)
Assert.Equal("Alice", sym.Symbol.Name)
Assert.Equal(SymbolKind.Field, sym.Symbol.Kind) ' Incorrectly returns Local
Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations(0)) ' Incorrect location
End Sub
<Fact>
<WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")>
Public Sub GetSymbolInfo_WithDuplicateInferredNames()
Dim source = "
Class C
Shared Sub M(Bob As String)
Dim x1 = (Bob, Bob)
End Sub
End Class
"
Dim tree = Parse(source, options:=TestOptions.Regular)
Dim comp = CreateCompilationWithMscorlib40(tree)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().Single()
Dim type = DirectCast(model.GetTypeInfo(tuple).Type, TypeSymbol)
Assert.True(type.TupleElementNames.IsDefault)
End Sub
<Fact>
Public Sub RetargetTupleErrorType()
Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class A
Public Shared Function M() As (Integer, Integer)
Return (1, 2)
End Function
End Class
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
libComp.AssertNoDiagnostics()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class B
Public Sub M2()
A.M()
End Sub
End Class
</file>
</compilation>, additionalRefs:={libComp.ToMetadataReference()})
comp.AssertTheseDiagnostics(
<errors>
BC30652: Reference required to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' containing the type 'ValueTuple(Of ,)'. Add one to your project.
A.M()
~~~~~
</errors>)
Dim methodM = comp.GetMember(Of MethodSymbol)("A.M")
Assert.Equal("(System.Int32, System.Int32)", methodM.ReturnType.ToTestDisplayString())
Assert.True(methodM.ReturnType.IsTupleType)
Assert.False(methodM.ReturnType.IsErrorType())
Assert.True(methodM.ReturnType.TupleUnderlyingType.IsErrorType())
End Sub
<Fact>
Public Sub CaseSensitivity001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x2 = (A:=10, B:=20)
System.Console.Write(x2.a)
System.Console.Write(x2.item2)
Dim x3 = (item1 := 1, item2 := 2)
System.Console.Write(x3.Item1)
System.Console.WriteLine(x3.Item2)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[102012]]>)
End Sub
<Fact>
Public Sub CaseSensitivity002()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
Dim x1 = (A:=10, a:=20)
System.Console.Write(x1.a)
System.Console.Write(x1.A)
Dim x2 as (A as Integer, a As Integer) = (10, 20)
System.Console.Write(x1.a)
System.Console.Write(x1.A)
Dim x3 = (I1:=10, item1:=20)
Dim x4 = (Item1:=10, item1:=20)
Dim x5 = (item1:=10, item1:=20)
Dim x6 = (tostring:=10, item1:=20)
End Sub
End Module
]]>
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37262: Tuple element names must be unique.
Dim x1 = (A:=10, a:=20)
~
BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'.
System.Console.Write(x1.a)
~~~~
BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'.
System.Console.Write(x1.A)
~~~~
BC37262: Tuple element names must be unique.
Dim x2 as (A as Integer, a As Integer) = (10, 20)
~
BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'.
System.Console.Write(x1.a)
~~~~
BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'.
System.Console.Write(x1.A)
~~~~
BC37261: Tuple element name 'item1' is only allowed at position 1.
Dim x3 = (I1:=10, item1:=20)
~~~~~
BC37261: Tuple element name 'item1' is only allowed at position 1.
Dim x4 = (Item1:=10, item1:=20)
~~~~~
BC37261: Tuple element name 'item1' is only allowed at position 1.
Dim x5 = (item1:=10, item1:=20)
~~~~~
BC37260: Tuple element name 'tostring' is disallowed at any position.
Dim x6 = (tostring:=10, item1:=20)
~~~~~~~~
BC37261: Tuple element name 'item1' is only allowed at position 1.
Dim x6 = (tostring:=10, item1:=20)
~~~~~
</errors>)
End Sub
<Fact>
Public Sub CaseSensitivity003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (Item1 as String, itEm2 as String, Bob as string) = (Nothing, Nothing, Nothing)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, , )
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(Nothing, Nothing, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Dim fields = From m In model.GetTypeInfo(node).ConvertedType.GetMembers()
Where m.Kind = SymbolKind.Field
Order By m.Name
Select m.Name
' check no duplication of original/default ItemX fields
Assert.Equal("Bob#Item1#Item2#Item3", fields.Join("#"))
End Sub
<Fact>
Public Sub CaseSensitivity004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (
I1 := 1,
I2 := 2,
I3 := 3,
ITeM4 := 4,
I5 := 5,
I6 := 6,
I7 := 7,
ITeM8 := 8,
ItEM9 := 9
)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(1, 2, 3, 4, 5, 6, 7, 8, 9)
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Dim fields = From m In model.GetTypeInfo(node).Type.GetMembers()
Where m.Kind = SymbolKind.Field
Order By m.Name
Select m.Name
' check no duplication of original/default ItemX fields
Assert.Equal("I1#I2#I3#I5#I6#I7#Item1#Item2#Item3#Item4#Item5#Item6#Item7#Item8#Item9#Rest", fields.Join("#"))
End Sub
' The NonNullTypes context for nested tuple types is using a dummy rather than actual context from surrounding code.
' This does not affect `IsNullable`, but it affects `IsAnnotatedWithNonNullTypesContext`, which is used in comparisons.
' So when we copy modifiers (re-applying nullability information, including actual NonNullTypes context), we make the comparison fail.
' I think the solution is to never use a dummy context, even for value types.
<Fact>
Public Sub TupleNamesFromCS001()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public (int Alice, int Bob) goo = (2, 3);
public (int Alice, int Bob) Bar() => (4, 5);
public (int Alice, int Bob) Baz => (6, 7);
}
public class Class2
{
public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) goo = SetBob(11);
public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Bar() => SetBob(12);
public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Baz => SetBob(13);
private static (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) SetBob(int x)
{
var result = default((int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob));
result.Bob = x;
return result;
}
}
public class class3: IEnumerable<(int Alice, int Bob)>
{
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator<(Int32 Alice, Int32 Bob)> IEnumerable<(Int32 Alice, Int32 Bob)>.GetEnumerator()
{
yield return (1, 2);
yield return (3, 4);
}
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Alice)
System.Console.WriteLine(x.goo.Bob)
System.Console.WriteLine(x.Bar.Alice)
System.Console.WriteLine(x.Bar.Bob)
System.Console.WriteLine(x.Baz.Alice)
System.Console.WriteLine(x.Baz.Bob)
Dim y As New ClassLibrary1.Class2
System.Console.WriteLine(y.goo.Alice)
System.Console.WriteLine(y.goo.Bob)
System.Console.WriteLine(y.Bar.Alice)
System.Console.WriteLine(y.Bar.Bob)
System.Console.WriteLine(y.Baz.Alice)
System.Console.WriteLine(y.Baz.Bob)
Dim z As New ClassLibrary1.class3
For Each item In z
System.Console.WriteLine(item.Alice)
System.Console.WriteLine(item.Bob)
Next
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation},
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="
2
3
4
5
6
7
0
11
0
12
0
13
1
2
3
4")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleNamesFromVB001()
Dim classLib = CreateVisualBasicCompilation("VBClass",
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Namespace ClassLibrary1
Public Class Class1
Public goo As (Alice As Integer, Bob As Integer) = (2, 3)
Public Function Bar() As (Alice As Integer, Bob As Integer)
Return (4, 5)
End Function
Public ReadOnly Property Baz As (Alice As Integer, Bob As Integer)
Get
Return (6, 7)
End Get
End Property
End Class
Public Class Class2
Public goo As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = SetBob(11)
Public Function Bar() As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer)
Return SetBob(12)
End Function
Public ReadOnly Property Baz As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer)
Get
Return SetBob(13)
End Get
End Property
Private Shared Function SetBob(x As Integer) As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer)
Dim result As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = Nothing
result.Bob = x
Return result
End Function
End Class
Public Class class3
Implements IEnumerable(Of (Alice As Integer, Bob As Integer))
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
Public Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator
Yield (1, 2)
Yield (3, 4)
End Function
End Class
End Namespace
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Alice)
System.Console.WriteLine(x.goo.Bob)
System.Console.WriteLine(x.Bar.Alice)
System.Console.WriteLine(x.Bar.Bob)
System.Console.WriteLine(x.Baz.Alice)
System.Console.WriteLine(x.Baz.Bob)
Dim y As New ClassLibrary1.Class2
System.Console.WriteLine(y.goo.Alice)
System.Console.WriteLine(y.goo.Bob)
System.Console.WriteLine(y.Bar.Alice)
System.Console.WriteLine(y.Bar.Bob)
System.Console.WriteLine(y.Baz.Alice)
System.Console.WriteLine(y.Baz.Bob)
Dim z As New ClassLibrary1.class3
For Each item In z
System.Console.WriteLine(item.Alice)
System.Console.WriteLine(item.Bob)
Next
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={classLib},
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="
2
3
4
5
6
7
0
11
0
12
0
13
1
2
3
4")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleNamesFromVB001_InterfaceImpl()
Dim classLib = CreateVisualBasicCompilation("VBClass",
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Namespace ClassLibrary1
Public Class class3
Implements IEnumerable(Of (Alice As Integer, Bob As Integer))
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
Private Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator
Yield (1, 2)
Yield (3, 4)
End Function
End Class
End Namespace
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim z As New ClassLibrary1.class3
For Each item In z
System.Console.WriteLine(item.Alice)
System.Console.WriteLine(item.Bob)
Next
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={classLib},
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="
1
2
3
4")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleNamesFromCS002()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public (int Alice, (int Alice, int Bob) Bob) goo = (2, (2, 3));
public ((int Alice, int Bob)[] Alice, int Bob) Bar() => (new(int, int)[] { (4, 5) }, 5);
public (int Alice, List<(int Alice, int Bob)?> Bob) Baz => (6, new List<(int Alice, int Bob)?>() { (8, 9) });
public static event Action<(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, (int Alice, int Bob) Bob)> goo1;
public static void raise()
{
goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42)));
}
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Bob.Bob)
System.Console.WriteLine(x.goo.Item2.Item2)
System.Console.WriteLine(x.Bar.Alice(0).Bob)
System.Console.WriteLine(x.Bar.Item1(0).Item2)
System.Console.WriteLine(x.Baz.Bob(0).Value)
System.Console.WriteLine(x.Baz.Item2(0).Value)
AddHandler ClassLibrary1.Class1.goo1, Sub(p)
System.Console.WriteLine(p.Bob.Bob)
System.Console.WriteLine(p.Rest.Item2.Bob)
End Sub
ClassLibrary1.Class1.raise()
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation},
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="
3
3
5
5
(8, 9)
(8, 9)
42
42")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleNamesFromVB002()
Dim classLib = CreateVisualBasicCompilation("VBClass",
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Namespace ClassLibrary1
Public Class Class1
Public goo As (Alice As Integer, Bob As (Alice As Integer, Bob As Integer)) = (2, (2, 3))
Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer)
Return (New(Integer, Integer)() {(4, 5)}, 5)
End Function
Public ReadOnly Property Baz As (Alice As Integer, Bob As List(Of (Alice As Integer, Bob As Integer) ?))
Get
Return (6, New List(Of (Alice As Integer, Bob As Integer) ?)() From {(8, 9)})
End Get
End Property
Public Shared Event goo1 As Action(Of (i0 As Integer, i1 As Integer, i2 As Integer, i3 As Integer, i4 As Integer, i5 As Integer, i6 As Integer, i7 As Integer, Bob As (Alice As Integer, Bob As Integer)))
Public Shared Sub raise()
RaiseEvent goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42)))
End Sub
End Class
End Namespace
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Bob.Bob)
System.Console.WriteLine(x.goo.Item2.Item2)
System.Console.WriteLine(x.Bar.Alice(0).Bob)
System.Console.WriteLine(x.Bar.Item1(0).Item2)
System.Console.WriteLine(x.Baz.Bob(0).Value)
System.Console.WriteLine(x.Baz.Item2(0).Value)
AddHandler ClassLibrary1.Class1.goo1, Sub(p)
System.Console.WriteLine(p.Bob.Bob)
System.Console.WriteLine(p.Rest.Item2.Bob)
End Sub
ClassLibrary1.Class1.raise()
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={classLib},
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="
3
3
5
5
(8, 9)
(8, 9)
42
42")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleNamesFromCS003()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public (int Alice, int alice) goo = (2, 3);
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Item1)
System.Console.WriteLine(x.goo.Item2)
System.Console.WriteLine(x.goo.Alice)
System.Console.WriteLine(x.goo.alice)
Dim f = x.goo
System.Console.WriteLine(f.Item1)
System.Console.WriteLine(f.Item2)
System.Console.WriteLine(f.Alice)
System.Console.WriteLine(f.alice)
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation},
referencedAssemblies:=s_valueTupleRefsAndDefault)
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(8, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(9, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(14, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(15, 34)
)
End Sub
<Fact>
Public Sub TupleNamesFromCS004()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public (int Alice, int alice, int) goo = (2, 3, 4);
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=s_valueTupleRefsAndDefault)
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Module Module1
Sub Main()
Dim x As New ClassLibrary1.Class1
System.Console.WriteLine(x.goo.Item1)
System.Console.WriteLine(x.goo.Item2)
System.Console.WriteLine(x.goo.Item3)
System.Console.WriteLine(x.goo.Alice)
System.Console.WriteLine(x.goo.alice)
Dim f = x.goo
System.Console.WriteLine(f.Item1)
System.Console.WriteLine(f.Item2)
System.Console.WriteLine(f.Item3)
System.Console.WriteLine(f.Alice)
System.Console.WriteLine(f.alice)
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation},
referencedAssemblies:=s_valueTupleRefsAndDefault)
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(9, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(10, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(16, 34),
Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(17, 34)
)
End Sub
<Fact>
Public Sub BadTupleNameMetadata()
Dim comp = CreateCompilationWithCustomILSource(<compilation>
<file name="a.vb">
</file>
</compilation>,
"
.assembly extern mscorlib { }
.assembly extern System.ValueTuple
{
.publickeytoken = (CC 7B 13 FF CD 2D DD 51 )
.ver 4:0:1:0
}
.class public auto ansi C
extends [mscorlib]System.Object
{
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField
.field public int32 ValidFieldWithAttribute
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[1](""name1"")}
= ( 01 00 01 00 00 00 05 6E 61 6D 65 31 )
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooFewNames
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[1](""name1"")}
= ( 01 00 01 00 00 00 05 6E 61 6D 65 31 )
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooManyNames
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[3](""e1"", ""e2"", ""e3"")}
= ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 )
.method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32>
TooFewNamesMethod() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[1](""name1"")}
= ( 01 00 01 00 00 00 05 6E 61 6D 65 31 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0,
!1)
IL_0007: ret
} // end of method C::TooFewNamesMethod
.method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32>
TooManyNamesMethod() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[3](""e1"", ""e2"", ""e3"")}
= ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0,
!1)
IL_0007: ret
} // end of method C::TooManyNamesMethod
} // end of class C
",
additionalReferences:=s_valueTupleRefs)
Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim validField = c.GetMember(Of FieldSymbol)("ValidField")
Assert.False(validField.Type.IsErrorType())
Assert.True(validField.Type.IsTupleType)
Assert.True(validField.Type.TupleElementNames.IsDefault)
Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute")
Assert.True(validFieldWithAttribute.Type.IsErrorType())
Assert.False(validFieldWithAttribute.Type.IsTupleType)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type)
Assert.False(DirectCast(validFieldWithAttribute.Type, INamedTypeSymbol).IsSerializable)
Dim tooFewNames = c.GetMember(Of FieldSymbol)("TooFewNames")
Assert.True(tooFewNames.Type.IsErrorType())
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNames.Type)
Assert.False(DirectCast(tooFewNames.Type, INamedTypeSymbol).IsSerializable)
Dim tooManyNames = c.GetMember(Of FieldSymbol)("TooManyNames")
Assert.True(tooManyNames.Type.IsErrorType())
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNames.Type)
Dim tooFewNamesMethod = c.GetMember(Of MethodSymbol)("TooFewNamesMethod")
Assert.True(tooFewNamesMethod.ReturnType.IsErrorType())
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNamesMethod.ReturnType)
Dim tooManyNamesMethod = c.GetMember(Of MethodSymbol)("TooManyNamesMethod")
Assert.True(tooManyNamesMethod.ReturnType.IsErrorType())
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNamesMethod.ReturnType)
End Sub
<Fact>
Public Sub MetadataForPartiallyNamedTuples()
Dim comp = CreateCompilationWithCustomILSource(<compilation>
<file name="a.vb">
</file>
</compilation>,
"
.assembly extern mscorlib { }
.assembly extern System.ValueTuple
{
.publickeytoken = (CC 7B 13 FF CD 2D DD 51 )
.ver 4:0:1:0
}
.class public auto ansi C
extends [mscorlib]System.Object
{
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField
.field public int32 ValidFieldWithAttribute
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[1](""name1"")}
= ( 01 00 01 00 00 00 05 6E 61 6D 65 31 )
// In source, all or no names must be specified for a tuple
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> PartialNames
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[2](""e1"", null)}
= ( 01 00 02 00 00 00 02 65 31 FF )
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> AllNullNames
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// = {string[2](null, null)}
= ( 01 00 02 00 00 00 ff ff 00 00 )
.method public hidebysig instance void PartialNamesMethod(
class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed
{
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// First null is fine (unnamed tuple) but the second is half-named
// = {string[3](null, ""e1"", null)}
= ( 01 00 03 00 00 00 FF 02 65 31 FF )
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::PartialNamesMethod
.method public hidebysig instance void AllNullNamesMethod(
class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed
{
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
// First null is fine (unnamed tuple) but the second is half-named
// = {string[3](null, null, null)}
= ( 01 00 03 00 00 00 ff ff ff 00 00 )
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::AllNullNamesMethod
} // end of class C
",
additionalReferences:=s_valueTupleRefs)
Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim validField = c.GetMember(Of FieldSymbol)("ValidField")
Assert.False(validField.Type.IsErrorType())
Assert.True(validField.Type.IsTupleType)
Assert.True(validField.Type.TupleElementNames.IsDefault)
Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute")
Assert.True(validFieldWithAttribute.Type.IsErrorType())
Assert.False(validFieldWithAttribute.Type.IsTupleType)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type)
Dim partialNames = c.GetMember(Of FieldSymbol)("PartialNames")
Assert.False(partialNames.Type.IsErrorType())
Assert.True(partialNames.Type.IsTupleType)
Assert.Equal("(e1 As System.Int32, System.Int32)", partialNames.Type.ToTestDisplayString())
Dim allNullNames = c.GetMember(Of FieldSymbol)("AllNullNames")
Assert.False(allNullNames.Type.IsErrorType())
Assert.True(allNullNames.Type.IsTupleType)
Assert.Equal("(System.Int32, System.Int32)", allNullNames.Type.ToTestDisplayString())
Dim partialNamesMethod = c.GetMember(Of MethodSymbol)("PartialNamesMethod")
Dim partialParamType = partialNamesMethod.Parameters.Single().Type
Assert.False(partialParamType.IsErrorType())
Assert.True(partialParamType.IsTupleType)
Assert.Equal("ValueTuple(Of (e1 As System.Int32, System.Int32))", partialParamType.ToTestDisplayString())
Dim allNullNamesMethod = c.GetMember(Of MethodSymbol)("AllNullNamesMethod")
Dim allNullParamType = allNullNamesMethod.Parameters.Single().Type
Assert.False(allNullParamType.IsErrorType())
Assert.True(allNullParamType.IsTupleType)
Assert.Equal("ValueTuple(Of (System.Int32, System.Int32))", allNullParamType.ToTestDisplayString())
End Sub
<Fact>
Public Sub NestedTuplesNoAttribute()
Dim comp = CreateCompilationWithCustomILSource(<compilation>
<file name="a.vb">
</file>
</compilation>,
"
.assembly extern mscorlib { }
.assembly extern System.ValueTuple
{
.publickeytoken = (CC 7B 13 FF CD 2D DD 51 )
.ver 4:0:1:0
}
.class public auto ansi beforefieldinit Base`1<T>
extends [mscorlib]System.Object
{
}
.class public auto ansi C
extends [mscorlib]System.Object
{
.field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> Field1
.field public class Base`1<class [System.ValueTuple]System.ValueTuple`1<
class [System.ValueTuple]System.ValueTuple`2<int32, int32>>> Field2;
} // end of class C
",
additionalReferences:=s_valueTupleRefs)
Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim base1 = comp.GlobalNamespace.GetTypeMember("Base")
Assert.NotNull(base1)
Dim field1 = c.GetMember(Of FieldSymbol)("Field1")
Assert.False(field1.Type.IsErrorType())
Assert.True(field1.Type.IsTupleType)
Assert.True(field1.Type.TupleElementNames.IsDefault)
Dim field2Type = DirectCast(c.GetMember(Of FieldSymbol)("Field2").Type, NamedTypeSymbol)
Assert.Equal(base1, field2Type.OriginalDefinition)
Assert.True(field2Type.IsGenericType)
Dim first = field2Type.TypeArguments(0)
Assert.True(first.IsTupleType)
Assert.Equal(1, first.TupleElementTypes.Length)
Assert.True(first.TupleElementNames.IsDefault)
Dim second = first.TupleElementTypes(0)
Assert.True(second.IsTupleType)
Assert.True(second.TupleElementNames.IsDefault)
Assert.Equal(2, second.TupleElementTypes.Length)
Assert.All(second.TupleElementTypes,
Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType))
End Sub
<Fact>
<WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")>
Public Sub BadOverloadWithTupleLiteralWithNaturalType()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub M(x As Integer)
End Sub
Sub M(x As String)
End Sub
Sub Main()
M((1, 2))
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(
<errors>
BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments:
'Public Sub M(x As Integer)': Value of type '(Integer, Integer)' cannot be converted to 'Integer'.
'Public Sub M(x As String)': Value of type '(Integer, Integer)' cannot be converted to 'String'.
M((1, 2))
~
</errors>)
End Sub
<Fact>
<WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")>
Public Sub BadOverloadWithTupleLiteralWithNothing()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub M(x As Integer)
End Sub
Sub M(x As String)
End Sub
Sub Main()
M((1, Nothing))
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(
<errors>
BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments:
'Public Sub M(x As Integer)': Value of type '(Integer, Object)' cannot be converted to 'Integer'.
'Public Sub M(x As String)': Value of type '(Integer, Object)' cannot be converted to 'String'.
M((1, Nothing))
~
</errors>)
End Sub
<Fact>
<WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")>
Public Sub BadOverloadWithTupleLiteralWithAddressOf()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub M(x As Integer)
End Sub
Sub M(x As String)
End Sub
Sub Main()
M((1, AddressOf Main))
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(
<errors>
BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments:
'Public Sub M(x As Integer)': Expression does not produce a value.
'Public Sub M(x As String)': Expression does not produce a value.
M((1, AddressOf Main))
~
</errors>)
End Sub
<Fact>
Public Sub TupleLiteralWithOnlySomeNames()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t As (Integer, String, Integer) = (1, b:="hello", Item3:=3)
console.write($"{t.Item1} {t.Item2} {t.Item3}")
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:="1 hello 3")
End Sub
<Fact()>
<WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")>
Public Sub TupleCoVariance()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of Out T)
Function M() As System.ValueTuple(Of Integer, T)
End Interface
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter.
Function M() As System.ValueTuple(Of Integer, T)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")>
Public Sub TupleCoVariance2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of Out T)
Function M() As (Integer, T)
End Interface
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter.
Function M() As (Integer, T)
~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")>
Public Sub TupleContraVariance()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of In T)
Sub M(x As (Boolean, T))
End Interface
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36727: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'In' type parameter.
Sub M(x As (Boolean, T))
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub DefiniteAssignment001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (A as string, B as string)
ss.A = "q"
ss.Item2 = "w"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, w)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment001Err()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (A as string, B as string)
ss.A = "q"
'ss.Item2 = "w"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, )]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(8, 34)
)
End Sub
<Fact>
Public Sub DefiniteAssignment002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (A as string, B as string)
ss.A = "q"
ss.B = "q"
ss.Item1 = "w"
ss.Item2 = "w"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(w, w)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (A as string, D as (B as string, C as string ))
ss.A = "q"
ss.D.B = "w"
ss.D.C = "e"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, (w, e))]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string ,
I2 As string,
I3 As string,
I4 As string,
I5 As string,
I6 As string,
I7 As string,
I8 As string,
I9 As string,
I10 As string)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
ss.I8 = "q"
ss.I9 = "q"
ss.I10 = "q"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.Item1 = "q"
ss.Item2 = "q"
ss.Item3 = "q"
ss.Item4 = "q"
ss.Item5 = "q"
ss.Item6 = "q"
ss.Item7 = "q"
ss.Item8 = "q"
ss.Item9 = "q"
ss.Item10 = "q"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.Item1 = "q"
ss.I2 = "q"
ss.Item3 = "q"
ss.I4 = "q"
ss.Item5 = "q"
ss.I6 = "q"
ss.Item7 = "q"
ss.I8 = "q"
ss.Item9 = "q"
ss.I10 = "q"
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.Item1 = "q"
ss.I2 = "q"
ss.Item3 = "q"
ss.I4 = "q"
ss.Item5 = "q"
ss.I6 = "q"
ss.Item7 = "q"
ss.I8 = "q"
ss.Item9 = "q"
ss.I10 = "q"
System.Console.WriteLine(ss.Rest)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment008()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.I8 = "q"
ss.Item9 = "q"
ss.I10 = "q"
System.Console.WriteLine(ss.Rest)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment008long()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String,
I11 as string,
I12 As String,
I13 As String,
I14 As String,
I15 As String,
I16 As String,
I17 As String,
I18 As String,
I19 As String,
I20 As String,
I21 as string,
I22 As String,
I23 As String,
I24 As String,
I25 As String,
I26 As String,
I27 As String,
I28 As String,
I29 As String,
I30 As String,
I31 As String)
'warn
System.Console.WriteLine(ss.Rest.Rest.Rest)
'warn
System.Console.WriteLine(ss.I31)
ss.I29 = "q"
ss.Item30 = "q"
ss.I31 = "q"
System.Console.WriteLine(ss.I29)
System.Console.WriteLine(ss.Rest.Rest.Rest)
System.Console.WriteLine(ss.I31)
' warn
System.Console.WriteLine(ss.Rest.Rest)
' warn
System.Console.WriteLine(ss.Rest)
' warn
System.Console.WriteLine(ss)
' warn
System.Console.WriteLine(ss.I2)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
(, , , , , , , , , )
q
(, , , , , , , q, q, q)
q
(, , , , , , , , , , , , , , q, q, q)
(, , , , , , , , , , , , , , , , , , , , , q, q, q)
(, , , , , , , , , , , , , , , , , , , , , , , , , , , , q, q, q)]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest.Rest").WithArguments("Rest").WithLocation(36, 34),
Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I31").WithArguments("I31").WithLocation(38, 34),
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest").WithArguments("Rest").WithLocation(49, 34),
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(52, 34),
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(55, 34),
Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I2").WithArguments("I2").WithLocation(58, 34))
End Sub
<Fact>
Public Sub DefiniteAssignment009()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
ss.Rest = Nothing
System.Console.WriteLine(ss)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, , , )]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment010()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String,
I9 As String,
I10 As String)
ss.Rest = ("q", "w", "e")
System.Console.WriteLine(ss.I9)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[w]]>)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DefiniteAssignment011()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
if (1.ToString() = 2.ToString())
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
ss.I8 = "q"
System.Console.WriteLine(ss)
elseif (1.ToString() = 3.ToString())
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
' ss.I8 = "q"
System.Console.WriteLine(ss)
else
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
' ss.I7 = "q"
ss.I8 = "q"
System.Console.WriteLine(ss) ' should fail
end if
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(44, 38),
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(65, 38)
)
End Sub
<Fact>
Public Sub DefiniteAssignment012()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
if (1.ToString() = 2.ToString())
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
ss.I8 = "q"
System.Console.WriteLine(ss)
else if (1.ToString() = 3.ToString())
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
' ss.I8 = "q"
System.Console.WriteLine(ss) ' should fail1
else
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
' ss.I7 = "q"
ss.I8 = "q"
System.Console.WriteLine(ss) ' should fail2
end if
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(43, 38),
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(64, 38)
)
End Sub
<Fact>
Public Sub DefiniteAssignment013()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.I2 = "q"
ss.I3 = "q"
ss.I4 = "q"
ss.I5 = "q"
ss.I6 = "q"
ss.I7 = "q"
ss.Item1 = "q"
ss.Item2 = "q"
ss.Item3 = "q"
ss.Item4 = "q"
ss.Item5 = "q"
ss.Item6 = "q"
ss.Item7 = "q"
System.Console.WriteLine(ss.Rest)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[()]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(28, 38)
)
End Sub
<Fact>
Public Sub DefiniteAssignment014()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim ss as (I1 as string,
I2 As String,
I3 As String,
I4 As String,
I5 As String,
I6 As String,
I7 As String,
I8 As String)
ss.I1 = "q"
ss.Item2 = "aa"
System.Console.WriteLine(ss.Item1)
System.Console.WriteLine(ss.I2)
System.Console.WriteLine(ss.I3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[q
aa]]>)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I3").WithArguments("I3").WithLocation(18, 38)
)
End Sub
<Fact>
Public Sub DefiniteAssignment015()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main()
Dim v = Test().Result
end sub
async Function Test() as Task(of long)
Dim v1 as (a as Integer, b as Integer)
Dim v2 as (x as Byte, y as Integer)
v1.a = 5
v2.x = 5 ' no need to persist across await since it is unused after it.
System.Console.WriteLine(v2.Item1)
await Task.Yield()
' this is assigned and persisted across await
return v1.Item1
end Function
End Module
</file>
</compilation>, useLatestFramework:=True, references:=s_valueTupleRefs, expectedOutput:="5")
' NOTE: !!! There should be NO IL local for " v1 as (Long, Integer)" , it should be captured instead
' NOTE: !!! There should be an IL local for " v2 as (Byte, Integer)" , it should not be captured
verifier.VerifyIL("Module1.VB$StateMachine_1_Test.MoveNext()", <![CDATA[
{
// Code size 214 (0xd6)
.maxstack 3
.locals init (Long V_0,
Integer V_1,
System.ValueTuple(Of Byte, Integer) V_2, //v2
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3,
System.Runtime.CompilerServices.YieldAwaitable V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld "Module1.VB$StateMachine_1_Test.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0061
IL_000a: ldarg.0
IL_000b: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)"
IL_0010: ldc.i4.5
IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0016: ldloca.s V_2
IL_0018: ldc.i4.5
IL_0019: stfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte"
IL_001e: ldloc.2
IL_001f: ldfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte"
IL_0024: call "Sub System.Console.WriteLine(Integer)"
IL_0029: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_002e: stloc.s V_4
IL_0030: ldloca.s V_4
IL_0032: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0037: stloc.3
IL_0038: ldloca.s V_3
IL_003a: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_003f: brtrue.s IL_007d
IL_0041: ldarg.0
IL_0042: ldc.i4.0
IL_0043: dup
IL_0044: stloc.1
IL_0045: stfld "Module1.VB$StateMachine_1_Test.$State As Integer"
IL_004a: ldarg.0
IL_004b: ldloc.3
IL_004c: stfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0051: ldarg.0
IL_0052: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)"
IL_0057: ldloca.s V_3
IL_0059: ldarg.0
IL_005a: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Module1.VB$StateMachine_1_Test)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Module1.VB$StateMachine_1_Test)"
IL_005f: leave.s IL_00d5
IL_0061: ldarg.0
IL_0062: ldc.i4.m1
IL_0063: dup
IL_0064: stloc.1
IL_0065: stfld "Module1.VB$StateMachine_1_Test.$State As Integer"
IL_006a: ldarg.0
IL_006b: ldfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0070: stloc.3
IL_0071: ldarg.0
IL_0072: ldflda "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0077: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_007d: ldloca.s V_3
IL_007f: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_0084: ldloca.s V_3
IL_0086: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_008c: ldarg.0
IL_008d: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)"
IL_0092: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0097: conv.i8
IL_0098: stloc.0
IL_0099: leave.s IL_00bf
}
catch System.Exception
{
IL_009b: dup
IL_009c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00a1: stloc.s V_5
IL_00a3: ldarg.0
IL_00a4: ldc.i4.s -2
IL_00a6: stfld "Module1.VB$StateMachine_1_Test.$State As Integer"
IL_00ab: ldarg.0
IL_00ac: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)"
IL_00b1: ldloc.s V_5
IL_00b3: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetException(System.Exception)"
IL_00b8: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00bd: leave.s IL_00d5
}
IL_00bf: ldarg.0
IL_00c0: ldc.i4.s -2
IL_00c2: dup
IL_00c3: stloc.1
IL_00c4: stfld "Module1.VB$StateMachine_1_Test.$State As Integer"
IL_00c9: ldarg.0
IL_00ca: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)"
IL_00cf: ldloc.0
IL_00d0: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetResult(Long)"
IL_00d5: ret
}
]]>)
End Sub
<Fact>
<WorkItem(13661, "https://github.com/dotnet/roslyn/issues/13661")>
Public Sub LongTupleWithPartialNames_Bug13661()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim t = (A:=1, 2, C:=3, D:=4, E:=5, F:=6, G:=7, 8, I:=9)
System.Console.Write($"{t.I}")
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs,
options:=TestOptions.DebugExe, expectedOutput:="9",
sourceSymbolValidator:=
Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim t = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0)
Dim xSymbol = DirectCast(model.GetDeclaredSymbol(t), LocalSymbol).Type
AssertEx.SetEqual(xSymbol.GetMembers().OfType(Of FieldSymbol)().Select(Function(f) f.Name),
"A", "C", "D", "E", "F", "G", "I", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Rest")
End Sub)
' No assert hit
End Sub
<Fact>
Public Sub UnifyUnderlyingWithTuple_08()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x = (1, 3)
Dim s As String = x
System.Console.WriteLine(s)
System.Console.WriteLine(CType(x, Long))
Dim y As (Integer, String) = New KeyValuePair(Of Integer, String)(2, "4")
System.Console.WriteLine(y)
System.Console.WriteLine(CType("5", ValueTuple(Of String, String)))
System.Console.WriteLine(+x)
System.Console.WriteLine(-x)
System.Console.WriteLine(Not x)
System.Console.WriteLine(If(x, True, False))
System.Console.WriteLine(If(Not x, True, False))
System.Console.WriteLine(x + 1)
System.Console.WriteLine(x - 1)
System.Console.WriteLine(x * 3)
System.Console.WriteLine(x / 2)
System.Console.WriteLine(x \ 2)
System.Console.WriteLine(x Mod 3)
System.Console.WriteLine(x & 3)
System.Console.WriteLine(x And 3)
System.Console.WriteLine(x Or 15)
System.Console.WriteLine(x Xor 3)
System.Console.WriteLine(x Like 15)
System.Console.WriteLine(x ^ 4)
System.Console.WriteLine(x << 1)
System.Console.WriteLine(x >> 1)
System.Console.WriteLine(x = 1)
System.Console.WriteLine(x <> 1)
System.Console.WriteLine(x > 1)
System.Console.WriteLine(x < 1)
System.Console.WriteLine(x >= 1)
System.Console.WriteLine(x <= 1)
End Sub
End Module
]]></file>
</compilation>
Dim tuple =
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
Me.Item1 = item1
Me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)) As String
Return arg.ToString()
End Operator
Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)) As Long
Return CLng(CObj(arg.Item1) + CObj(arg.Item2))
End Operator
Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2)
Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value)
End Operator
Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2)
Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2))
End Operator
Public Shared Operator +(arg As ValueTuple(Of T1, T2)) As ValueTuple(Of T1, T2)
Return arg
End Operator
Public Shared Operator -(arg As ValueTuple(Of T1, T2)) As Long
Return -CType(arg, Long)
End Operator
Public Shared Operator Not(arg As ValueTuple(Of T1, T2)) As Boolean
Return CType(arg, Long) = 0
End Operator
Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)) As Boolean
Return CType(arg, Long) <> 0
End Operator
Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)) As Boolean
Return CType(arg, Long) = 0
End Operator
Public Shared Operator +(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) + arg2
End Operator
Public Shared Operator -(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) - arg2
End Operator
Public Shared Operator *(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) * arg2
End Operator
Public Shared Operator /(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) / arg2
End Operator
Public Shared Operator \(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) \ arg2
End Operator
Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) Mod arg2
End Operator
Public Shared Operator &(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) & arg2
End Operator
Public Shared Operator And(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) And arg2
End Operator
Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long
Return CType(arg1, Long) Or arg2
End Operator
Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long
Return CType(arg1, Long) Xor arg2
End Operator
Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long
Return CType(arg1, Long) Or arg2
End Operator
Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) ^ arg2
End Operator
Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) << arg2
End Operator
Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long
Return CType(arg1, Long) >> arg2
End Operator
Public Shared Operator =(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) = arg2
End Operator
Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) <> arg2
End Operator
Public Shared Operator >(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) > arg2
End Operator
Public Shared Operator <(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) < arg2
End Operator
Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) >= arg2
End Operator
Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean
Return CType(arg1, Long) <= arg2
End Operator
Public Overrides Function Equals(obj As Object) As Boolean
Return False
End Function
Public Overrides Function GetHashCode() As Integer
Return 0
End Function
End Structure
End Namespace
]]></file>
</compilation>
Dim expectedOutput =
"{1, 3}
4
{2, 4}
{5, 5}
{1, 3}
-4
False
True
False
5
3
12
2
2
1
43
0
15
7
15
256
8
2
False
True
True
False
True
False
"
Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll)
[lib].VerifyEmitDiagnostics()
Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()})
CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics()
Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()})
CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics()
End Sub
<Fact>
Public Sub UnifyUnderlyingWithTuple_12()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x? = (1, 3)
Dim s As String = x
System.Console.WriteLine(s)
System.Console.WriteLine(CType(x, Long))
Dim y As (Integer, String)? = New KeyValuePair(Of Integer, String)(2, "4")
System.Console.WriteLine(y)
System.Console.WriteLine(CType("5", ValueTuple(Of String, String)))
System.Console.WriteLine(+x)
System.Console.WriteLine(-x)
System.Console.WriteLine(Not x)
System.Console.WriteLine(If(x, True, False))
System.Console.WriteLine(If(Not x, True, False))
System.Console.WriteLine(x + 1)
System.Console.WriteLine(x - 1)
System.Console.WriteLine(x * 3)
System.Console.WriteLine(x / 2)
System.Console.WriteLine(x \ 2)
System.Console.WriteLine(x Mod 3)
System.Console.WriteLine(x & 3)
System.Console.WriteLine(x And 3)
System.Console.WriteLine(x Or 15)
System.Console.WriteLine(x Xor 3)
System.Console.WriteLine(x Like 15)
System.Console.WriteLine(x ^ 4)
System.Console.WriteLine(x << 1)
System.Console.WriteLine(x >> 1)
System.Console.WriteLine(x = 1)
System.Console.WriteLine(x <> 1)
System.Console.WriteLine(x > 1)
System.Console.WriteLine(x < 1)
System.Console.WriteLine(x >= 1)
System.Console.WriteLine(x <= 1)
End Sub
End Module
]]></file>
</compilation>
Dim tuple =
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
Me.Item1 = item1
Me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)?) As String
Return arg.ToString()
End Operator
Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)?) As Long
Return CLng(CObj(arg.Value.Item1) + CObj(arg.Value.Item2))
End Operator
Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2)?
Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value)
End Operator
Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2)?
Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2))
End Operator
Public Shared Operator +(arg As ValueTuple(Of T1, T2)?) As ValueTuple(Of T1, T2)?
Return arg
End Operator
Public Shared Operator -(arg As ValueTuple(Of T1, T2)?) As Long
Return -CType(arg, Long)
End Operator
Public Shared Operator Not(arg As ValueTuple(Of T1, T2)?) As Boolean
Return CType(arg, Long) = 0
End Operator
Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)?) As Boolean
Return CType(arg, Long) <> 0
End Operator
Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)?) As Boolean
Return CType(arg, Long) = 0
End Operator
Public Shared Operator +(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) + arg2
End Operator
Public Shared Operator -(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) - arg2
End Operator
Public Shared Operator *(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) * arg2
End Operator
Public Shared Operator /(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) / arg2
End Operator
Public Shared Operator \(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) \ arg2
End Operator
Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) Mod arg2
End Operator
Public Shared Operator &(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) & arg2
End Operator
Public Shared Operator And(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) And arg2
End Operator
Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long
Return CType(arg1, Long) Or arg2
End Operator
Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long
Return CType(arg1, Long) Xor arg2
End Operator
Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long
Return CType(arg1, Long) Or arg2
End Operator
Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) ^ arg2
End Operator
Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) << arg2
End Operator
Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long
Return CType(arg1, Long) >> arg2
End Operator
Public Shared Operator =(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) = arg2
End Operator
Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) <> arg2
End Operator
Public Shared Operator >(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) > arg2
End Operator
Public Shared Operator <(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) < arg2
End Operator
Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) >= arg2
End Operator
Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean
Return CType(arg1, Long) <= arg2
End Operator
Public Overrides Function Equals(obj As Object) As Boolean
Return False
End Function
Public Overrides Function GetHashCode() As Integer
Return 0
End Function
End Structure
End Namespace
]]></file>
</compilation>
Dim expectedOutput =
"{1, 3}
4
{2, 4}
{5, 5}
{1, 3}
-4
False
True
False
5
3
12
2
2
1
43
0
15
7
15
256
8
2
False
True
True
False
True
False
"
Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll)
[lib].VerifyEmitDiagnostics()
Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()})
CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics()
Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()})
CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics()
End Sub
<Fact>
Public Sub TupleConversion01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module C
Sub Main()
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
End Sub
End Module
]]></file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
~~~~
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'.
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'.
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
~~~~
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleConversion01_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module C
Sub Main()
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
End Sub
End Module
]]></file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'.
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long))
~~~~
BC30512: Option Strict On disallows implicit conversions from '(c As Integer, d As Integer)' to '(a As Short, b As Short)'.
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'.
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'.
Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer))
~~~~
BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'.
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'.
Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long))
~~~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(11288, "https://github.com/dotnet/roslyn/issues/11288")>
Public Sub TupleConversion02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long))
End Sub
End Module
<%= s_trivial2uple %><%= s_trivial3uple %>
</file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(c As Long, d As Long)'.
Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long))
~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleConvertedType01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String)? = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Dim typeInfo As TypeInfo = model.GetTypeInfo(node)
Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim e = node.Arguments(0).Expression
Assert.Equal("1", e.ToString())
typeInfo = model.GetTypeInfo(e)
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind)
Dim f = node.Arguments(1).Expression
Assert.Equal("""hello""", f.ToString())
typeInfo = model.GetTypeInfo(f)
Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType01_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Module C
Sub Main()
Dim x As (a As Short, b As String)? = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType01insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)?)
Dim y As Short? = DirectCast(11, Short?)
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2)
Assert.Equal("11", l11.ToString())
Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString())
Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind)
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType01insourceImplicit()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String)? = (1, "hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, ""hello"")", node.ToString())
Dim typeInfo As TypeInfo = model.GetTypeInfo(node)
Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
CompileAndVerify(comp)
End Sub
<Fact>
Public Sub TupleConvertedType02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String)? = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Dim typeInfo As TypeInfo = model.GetTypeInfo(node)
Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim e = node.Arguments(0).Expression
Assert.Equal("1", e.ToString())
typeInfo = model.GetTypeInfo(e)
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind)
Dim f = node.Arguments(1).Expression
Assert.Equal("""hello""", f.ToString())
typeInfo = model.GetTypeInfo(f)
Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType02insource00()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Short, d As String))", node.Parent.ToString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType02insource00_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Module C
Sub Main()
Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType02insource01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x = (e:=1, f:="hello")
Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent
Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString())
Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single()
Assert.Equal("(x)", x.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind)
End Sub
<Fact>
Public Sub TupleConvertedType02insource01_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Module C
Sub Main()
Dim x = (e:=1, f:="hello")
Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent
Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString())
Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single()
Assert.Equal("(x)", x.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind)
End Sub
<Fact>
Public Sub TupleConvertedType02insource02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x = (e:=1, f:="hello")
Dim x1 As (a As Object, b As String)? = DirectCast((x), (c As Long, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent
Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString())
Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Object, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single()
Assert.Equal("(x)", x.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind)
End Sub
<Fact>
Public Sub TupleConvertedType03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Integer, b As String)? = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType03insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)?)
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Integer, d As String)?)", node.Parent.ToString())
Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind)
Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNullable, model.GetConversion(node.Parent).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Integer, b As String) = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(a As System.Int32, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType05insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType05insource_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Module C
Sub Main()
Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String))
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String) = (e:=1, f:="hello")
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim e = node.Arguments(0).Expression
Assert.Equal("1", e.ToString())
Dim typeInfo = model.GetTypeInfo(e)
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind)
Dim f = node.Arguments(1).Expression
Assert.Equal("""hello""", f.ToString())
typeInfo = model.GetTypeInfo(f)
Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedType06insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String) = DirectCast((e:=1, f:="hello"), (c As Short, d As String))
Dim y As Short = DirectCast(11, short)
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2)
Assert.Equal("11", l11.ToString())
Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString())
Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind)
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=""hello"")", node.ToString())
Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedTypeNull01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String) = (e:=1, f:=Nothing)
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedTypeNull01insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module C
Sub Main()
Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=Nothing), (c As Short, d As String))
Dim y As String = DirectCast(Nothing, String)
End Sub
End Module
<%= s_trivial2uple %>
</file>
</compilation>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim lnothing = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2)
Assert.Equal("Nothing", lnothing.ToString())
Assert.Null(model.GetTypeInfo(lnothing).Type)
Assert.Equal("System.Object", model.GetTypeInfo(lnothing).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningNothingLiteral, model.GetConversion(lnothing).Kind)
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind)
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq"))
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim s As String
Public Sub New(ByVal arg As String)
s = arg + "1"
End Sub
Public Shared Narrowing Operator CType(ByVal arg As C1) As String
Return arg.s
End Operator
End Class
End Class
<%= s_trivial2uple %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString())
Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
CompileAndVerify(comp, expectedOutput:="{1, qq1}")
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC01_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Class C
Shared Sub Main()
Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq"))
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim s As String
Public Sub New(ByVal arg As String)
s = arg + "1"
End Sub
Public Shared Narrowing Operator CType(ByVal arg As C1) As String
Return arg.s
End Operator
End Class
End Class
<%= s_trivial2uple %>
</file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'.
Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq"))
~~~~
BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'.
Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq"))
~~~~~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'C.C1' to 'String'.
Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq"))
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC01insource()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=New C1("qq")), (c As Short, d As String))
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim s As String
Public Sub New(ByVal arg As String)
s = arg + "1"
End Sub
Public Shared Narrowing Operator CType(ByVal arg As C1) As String
Return arg.s
End Operator
End Class
End Class
<%= s_trivial2uple %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString())
Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind)
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind)
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString())
CompileAndVerify(comp, expectedOutput:="{1, qq1}")
End Sub
<Fact>
<WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")>
Public Sub TupleConvertedTypeUDC02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As C1 = (1, "qq")
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
Return New C1(arg)
End Operator
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
<%= s_trivial2uple %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(1, ""qq"")", node.ToString())
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
CompileAndVerify(comp, expectedOutput:="{1, qq}")
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim x As C1 = ("1", "qq")
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
Return New C1(arg)
End Operator
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
</errors>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(""1"", ""qq"")", node.ToString())
Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
CompileAndVerify(comp, expectedOutput:="(1, qq)")
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC03_StrictOn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Class C
Shared Sub Main()
Dim x As C1 = ("1", "qq")
System.Console.Write(x.ToString())
End Sub
Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
Return New C1(arg)
End Operator
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from '(String, String)' to 'C.C1'.
Dim x As C1 = ("1", "qq")
~~~~~~~~~~~
</errors>)
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(""1"", ""qq"")", node.ToString())
Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
End Sub
<Fact>
<WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")>
Public Sub TupleConvertedTypeUDC04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim x As C1 = (1, "qq")
System.Console.Write(x.ToString())
End Sub
Public Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1
Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte),
DirectCast(DirectCast(arg.Item2, Object), String)))
End Operator
End Structure
End Namespace
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics()
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().First()
Assert.Equal("(1, ""qq"")", node.ToString())
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
CompileAndVerify(comp, expectedOutput:="{1, qq}")
End Sub
<Fact>
<WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")>
Public Sub TupleConvertedTypeUDC05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim x As C1 = (1, "qq")
System.Console.Write(x.ToString())
End Sub
Public Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
System.Console.Write("C1")
Return New C1(arg)
End Operator
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1
System.Console.Write("VT ")
Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte),
DirectCast(DirectCast(arg.Item2, Object), String)))
End Operator
End Structure
End Namespace
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics()
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().First()
Assert.Equal("(1, ""qq"")", node.ToString())
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
CompileAndVerify(comp, expectedOutput:="VT {1, qq}")
End Sub
<Fact>
<WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")>
Public Sub TupleConvertedTypeUDC06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim x As C1 = (1, Nothing)
System.Console.Write(x.ToString())
End Sub
Public Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
System.Console.Write("C1")
Return New C1(arg)
End Operator
Public Overrides Function ToString() As String
Return val.ToString()
End Function
End Class
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}"
End Function
Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1
System.Console.Write("VT ")
Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte),
DirectCast(DirectCast(arg.Item2, Object), String)))
End Operator
End Structure
End Namespace
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics()
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().First()
Assert.Equal("(1, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind)
CompileAndVerify(comp, expectedOutput:="VT {1, }")
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC07_StrictOff_Narrowing()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim x As C1 = M1()
System.Console.Write(x.ToString())
End Sub
Shared Function M1() As (Integer, String)
Return (1, "qq")
End Function
Public Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1
System.Console.Write("C1 ")
Return New C1(arg)
End Operator
End Class
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
CompileAndVerify(comp, expectedOutput:="C1 C+C1")
End Sub
<Fact>
Public Sub TupleConvertedTypeUDC07()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Public Class C
Shared Sub Main()
Dim x As C1 = M1()
System.Console.Write(x.ToString())
End Sub
Shared Function M1() As (Integer, String)
Return (1, "qq")
End Function
Public Class C1
Public Dim val As (Byte, String)
Public Sub New(ByVal arg As (Byte, String))
val = arg
End Sub
Public Shared Widening Operator CType(ByVal arg As (Byte, String)) As C1
System.Console.Write("C1 ")
Return New C1(arg)
End Operator
End Class
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30512: Option Strict On disallows implicit conversions from '(Integer, String)' to 'C.C1'.
Dim x As C1 = M1()
~~~~
</errors>)
End Sub
<Fact>
Public Sub Inference01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((Nothing, Nothing))
Test((1, 1))
Test((Function() 7, Function() 8), 2)
End Sub
Shared Sub Test(Of T)(x As (T, T))
System.Console.WriteLine("first")
End Sub
Shared Sub Test(x As (Object, Object))
System.Console.WriteLine("second")
End Sub
Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T)), y As T)
System.Console.WriteLine("third")
System.Console.WriteLine(x.Item1().ToString())
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
second
first
third
7
")
End Sub
<Fact>
Public Sub Inference02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test1((Function() 7, Function() 8))
Test2(Function() 7, Function() 8)
Test3((Function() 7, Function() 8))
End Sub
Shared Sub Test1(Of T)(x As (T, T))
System.Console.WriteLine("first")
End Sub
Shared Sub Test1(x As (Object, Object))
System.Console.WriteLine("second")
End Sub
Shared Sub Test1(Of T)(x As (System.Func(Of T), System.Func(Of T)))
System.Console.WriteLine("third")
End Sub
Shared Sub Test2(Of T)(x As T, y As T)
System.Console.WriteLine("first")
End Sub
Shared Sub Test2(x As Object, y As Object)
System.Console.WriteLine("second")
End Sub
Shared Sub Test2(Of T)(x As System.Func(Of T), y As System.Func(Of T))
System.Console.WriteLine("third")
End Sub
Shared Sub Test3(Of T)(x As (T, T)?)
System.Console.WriteLine("first")
End Sub
Shared Sub Test3(x As (Object, Object)?)
System.Console.WriteLine("second")
End Sub
Shared Sub Test3(Of T)(x As (System.Func(Of T), System.Func(Of T))?)
System.Console.WriteLine("third")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
first
first
first")
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test1((Function() 7, Function() 8))
Test2(Function() 7, Function() 8)
Test3((Function() 7, Function() 8))
End Sub
Shared Sub Test1(x As (System.Func(Of Integer), System.Func(Of Integer)))
System.Console.WriteLine("second")
End Sub
Shared Sub Test1(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer)))
System.Console.WriteLine("third")
End Sub
Shared Sub Test2(x As System.Func(Of Integer), y As System.Func(Of Integer))
System.Console.WriteLine("second")
End Sub
Shared Sub Test2(x As System.Func(Of Integer, Integer), y As System.Func(Of Integer, Integer))
System.Console.WriteLine("third")
End Sub
Shared Sub Test3(x As (System.Func(Of Integer), System.Func(Of Integer))?)
System.Console.WriteLine("second")
End Sub
Shared Sub Test3(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer))?)
System.Console.WriteLine("third")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
second
second
second")
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim int = 1
Dim a = Function(x as Integer) x
Test1(a, int)
Test2((a, int))
Test3((a, int))
Dim b = (a, int)
Test2(b)
Test3(b)
End Sub
Shared Sub Test1(x As System.Action(Of Integer), y As Integer)
System.Console.WriteLine("second")
End Sub
Shared Sub Test1(x As System.Func(Of Integer, Integer), y As Integer)
System.Console.WriteLine("third")
End Sub
Shared Sub Test2(x As (System.Action(Of Integer), Integer))
System.Console.WriteLine("second")
End Sub
Shared Sub Test2(x As (System.Func(Of Integer, Integer), Integer))
System.Console.WriteLine("third")
End Sub
Shared Sub Test3(x As (System.Action(Of Integer), Integer)?)
System.Console.WriteLine("second")
End Sub
Shared Sub Test3(x As (System.Func(Of Integer, Integer), Integer)?)
System.Console.WriteLine("third")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
third
third
third
third
third")
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim x00 As (Integer, Func(Of Integer)) = (int, Function() int)
Dim x01 As (Integer, Func(Of Long)) = (int, Function() int)
Dim x02 As (Integer, Action) = (int, Function() int)
Dim x03 As (Integer, Object) = (int, Function() int)
Dim x04 As (Integer, Func(Of Short)) = (int, Function() int)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray()
AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda)
AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening,
ConversionKind.Identity,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening)
AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs,
ConversionKind.Identity,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs)
AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda,
ConversionKind.Identity,
ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda)
AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Identity,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim x00 As (Func(Of Integer), Integer) = (Function() int, int)
Dim x01 As (Func(Of Long), Integer) = (Function() int, int)
Dim x02 As (Action, Integer) = (Function() int, int)
Dim x03 As (Object, Integer) = (Function() int, int)
Dim x04 As (Func(Of Short), Integer) = (Function() int, int)
Dim x05 As (Func(Of Short), Func(Of Long)) = (Function() int, Function() int)
Dim x06 As (Func(Of Long), Func(Of Short)) = (Function() int, Function() int)
Dim x07 As (Short, (Func(Of Long), Func(Of Short))) = (int, (Function() int, Function() int))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray()
AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Widening Or ConversionKind.Lambda, ConversionKind.Identity)
AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening,
ConversionKind.Identity)
AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs,
ConversionKind.Identity)
AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda,
ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda,
ConversionKind.Identity)
AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Identity)
AssertConversions(model, nodes(5), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening)
AssertConversions(model, nodes(6), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing)
AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.NarrowingNumeric,
ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim x00 As (Integer, Func(Of Integer))? = (int, Function() int)
Dim x01 As (Short, Func(Of Long))? = (int, Function() int)
Dim x02 As (Integer, Action)? = (int, Function() int)
Dim x03 As (Integer, Object)? = (int, Function() int)
Dim x04 As (Integer, Func(Of Short))? = (int, Function() int)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray()
AssertConversions(model, nodes(0), ConversionKind.WideningNullableTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda)
AssertConversions(model, nodes(1), ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening,
ConversionKind.NarrowingNumeric,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening)
AssertConversions(model, nodes(2), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs,
ConversionKind.Identity,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs)
AssertConversions(model, nodes(3), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda,
ConversionKind.Identity,
ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda)
AssertConversions(model, nodes(4), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing,
ConversionKind.Identity,
ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim t = (int, Function() int)
Dim x00 As (Integer, Func(Of Integer)) = t
Dim x01 As (Integer, Func(Of Long)) = t
Dim x02 As (Integer, Action) = t
Dim x03 As (Integer, Object) = t
Dim x04 As (Integer, Func(Of Short)) = t
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray()
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(nodes(0)).Kind)
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind)
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind)
Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind)
Assert.Equal(ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_07()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim t = (int, Function() int)
Dim x00 As (Integer, Func(Of Integer))? = t
Dim x01 As (Integer, Func(Of Long))? = t
Dim x02 As (Integer, Action)? = t
Dim x03 As (Integer, Object)? = t
Dim x04 As (Integer, Func(Of Short))? = t
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray()
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_08()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim t? = (int, Function() int)
Dim x00 As (Integer, Func(Of Integer))? = t
Dim x01 As (Integer, Func(Of Long))? = t
Dim x02 As (Integer, Action)? = t
Dim x03 As (Integer, Object)? = t
Dim x04 As (Integer, Func(Of Short))? = t
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray()
Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind)
Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind)
End Sub
<Fact>
Public Sub DelegateRelaxationLevel_09()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Public Class C
Shared Sub Main()
Dim int as integer = 1
Dim t? = (int, Function() int)
Dim x00 As (Integer, Func(Of Integer)) = t
Dim x01 As (Integer, Func(Of Long)) = t
Dim x02 As (Integer, Action) = t
Dim x03 As (Integer, Object) = t
Dim x04 As (Integer, Func(Of Short)) = t
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray()
Assert.Equal(ConversionKind.NarrowingNullableTuple, model.GetConversion(nodes(0)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind)
Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind)
End Sub
<Fact>
Public Sub AnonymousDelegate_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim int = 1
Dim a = Function(x as Integer) x
Test1(a)
Test2((a, int))
Test3((a, int))
Dim b = (a, int)
Test2(b)
Test3(b)
End Sub
Shared Sub Test1(x As Object)
System.Console.WriteLine("second")
End Sub
Shared Sub Test2(x As (Object, Integer))
System.Console.WriteLine("second")
End Sub
Shared Sub Test3(x As (Object, Integer)?)
System.Console.WriteLine("second")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
second
second
second
second
second")
End Sub
<Fact>
<WorkItem(14529, "https://github.com/dotnet/roslyn/issues/14529")>
<WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")>
Public Sub AnonymousDelegate_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim int = 1
Dim a = Function(x as Integer) x
Test1(a)
Test2((a, int))
Test3((a, int))
Dim b = (a, int)
Test2(b)
Test3(b)
Test4({a})
End Sub
Shared Sub Test1(Of T)(x As System.Func(Of T, T))
System.Console.WriteLine("third")
End Sub
Shared Sub Test2(Of T)(x As (System.Func(Of T, T), Integer))
System.Console.WriteLine("third")
End Sub
Shared Sub Test3(Of T)(x As (System.Func(Of T, T), Integer)?)
System.Console.WriteLine("third")
End Sub
Shared Sub Test4(Of T)(x As System.Func(Of T, T)())
System.Console.WriteLine("third")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
third
third
third
third
third
third")
End Sub
<Fact>
Public Sub UserDefinedConversions_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub Main()
Dim int = 1
Dim tuple = (int, int)
Dim a as (A, Integer) = tuple
Dim b as (A, Integer) = (int, int)
Dim c as (A, Integer)? = tuple
Dim d as (A, Integer)? = (int, int)
System.Console.WriteLine(a)
System.Console.WriteLine(b)
System.Console.WriteLine(c)
System.Console.WriteLine(d)
End Sub
End Class
Class A
Public Shared Widening Operator CType(val As String) As A
System.Console.WriteLine(val)
Return New A()
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
1
1
1
1
(A, 1)
(A, 1)
(A, 1)
(A, 1)")
End Sub
<Fact>
Public Sub UserDefinedConversions_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub Main()
Dim int = 1
Dim val as new B()
Dim tuple = (val, int)
Dim a as (Integer, Integer) = tuple
Dim b as (Integer, Integer) = (val, int)
Dim c as (Integer, Integer)? = tuple
Dim d as (Integer, Integer)? = (val, int)
System.Console.WriteLine(a)
System.Console.WriteLine(b)
System.Console.WriteLine(c)
System.Console.WriteLine(d)
End Sub
End Class
Class B
Public Shared Widening Operator CType(val As B) As String
System.Console.WriteLine(val Is Nothing)
Return "2"
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
False
False
False
False
(2, 1)
(2, 1)
(2, 1)
(2, 1)")
End Sub
<Fact>
<WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")>
Public Sub UserDefinedConversions_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class C
Shared Sub Main()
Dim int = 1
Dim ad = Function() 2
Dim tuple = (ad, int)
Dim a as (A, Integer) = tuple
Dim b as (A, Integer) = (ad, int)
Dim c as (A, Integer)? = tuple
Dim d as (A, Integer)? = (ad, int)
System.Console.WriteLine(a)
System.Console.WriteLine(b)
System.Console.WriteLine(c)
System.Console.WriteLine(d)
End Sub
End Class
Class A
Public Shared Widening Operator CType(val As System.Func(Of Integer, Integer)) As A
System.Console.WriteLine(val)
Return New A()
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.Func`2[System.Int32,System.Int32]
System.Func`2[System.Int32,System.Int32]
System.Func`2[System.Int32,System.Int32]
System.Func`2[System.Int32,System.Int32]
(A, 1)
(A, 1)
(A, 1)
(A, 1)")
End Sub
<Fact>
Public Sub Inference02_Addressof()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Function M() As Integer
Return 7
End Function
Shared Sub Main()
Test((AddressOf M, AddressOf M))
End Sub
Shared Sub Test(Of T)(x As (T, T))
System.Console.WriteLine("first")
End Sub
Shared Sub Test(x As (Object, Object))
System.Console.WriteLine("second")
End Sub
Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T)))
System.Console.WriteLine("third")
System.Console.WriteLine(x.Item1().ToString())
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
third
7
")
End Sub
<Fact>
Public Sub Inference03_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((Function(x) x, Function(x) x))
End Sub
Shared Sub Test(Of T)(x As (T, T))
End Sub
Shared Sub Test(x As (Object, Object))
End Sub
Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T)))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments:
'Public Shared Sub Test(Of <generated method>)(x As (<generated method>, <generated method>))': Not most specific.
'Public Shared Sub Test(Of Integer)(x As (Func(Of Integer, Integer), Func(Of Integer, Integer)))': Not most specific.
Test((Function(x) x, Function(x) x))
~~~~
]]></expected>)
End Sub
<Fact>
Public Sub Inference03_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((Function(x) x, Function(x) x))
End Sub
Shared Sub Test(x As (Object, Object))
System.Console.WriteLine("second")
End Sub
Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T)))
System.Console.WriteLine("third")
System.Console.WriteLine(x.Item1(5).ToString())
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
third
5
")
End Sub
<Fact>
Public Sub Inference03_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((Function(x) x, Function(x) x))
End Sub
Shared Sub Test(Of T)(x As T, y As T)
System.Console.WriteLine("first")
End Sub
Shared Sub Test(x As (Object, Object))
System.Console.WriteLine("second")
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
second
")
End Sub
<Fact>
Public Sub Inference05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test((Function(x) x.x, Function(x) x.Item2))
Test((Function(x) x.bob, Function(x) x.Item1))
End Sub
Shared Sub Test(Of T)(x As (f1 As Func(Of (x As Byte, y As Byte), T), f2 As Func(Of (Integer, Integer), T)))
Console.WriteLine("first")
Console.WriteLine(x.f1((2, 3)).ToString())
Console.WriteLine(x.f2((2, 3)).ToString())
End Sub
Shared Sub Test(Of T)(x As (f1 As Func(Of (alice As Integer, bob As Integer), T), f2 As Func(Of (Integer, Integer), T)))
Console.WriteLine("second")
Console.WriteLine(x.f1((4, 5)).ToString())
Console.WriteLine(x.f2((4, 5)).ToString())
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="first
2
3
second
5
4
")
End Sub
<Fact>
Public Sub Inference08()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:=1, b:=2), (c:=3, d:=4))
Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.Item2)
Test2((a:=1, b:=2), (a:=3, b:=4), Function(t) t.a)
Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.a)
End Sub
Shared Sub Test1(Of T)(x As T, y As T)
Console.WriteLine("test1")
Console.WriteLine(x)
End Sub
Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer))
Console.WriteLine("test2_1")
Console.WriteLine(f(x))
End Sub
Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer))
Console.WriteLine("test2_2")
Console.WriteLine(f(x))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
test1
(1, 2)
test2_1
2
test2_1
1
test2_2
1
")
End Sub
<Fact>
Public Sub Inference08t()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim ab = (a:=1, b:=2)
Dim cd = (c:=3, d:=4)
Test1(ab, cd)
Test2(ab, cd, Function(t) t.Item2)
Test2(ab, ab, Function(t) t.a)
Test2(ab, cd, Function(t) t.a)
End Sub
Shared Sub Test1(Of T)(x As T, y As T)
Console.WriteLine("test1")
Console.WriteLine(x)
End Sub
Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer))
Console.WriteLine("test2_1")
Console.WriteLine(f(x))
End Sub
Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer))
Console.WriteLine("test2_2")
Console.WriteLine(f(x))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
test1
(1, 2)
test2_1
2
test2_1
1
test2_2
1
")
End Sub
<Fact>
Public Sub Inference09()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:=1, b:=2), DirectCast(1, ValueType))
End Sub
Shared Sub Test1(Of T)(x As T, y As T)
Console.Write(GetType(T))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="System.ValueType")
End Sub
<Fact>
Public Sub Inference10()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim t = (a:=1, b:=2)
Test1(t, DirectCast(1, ValueType))
End Sub
Shared Sub Test1(Of T)(ByRef x As T, y As T)
Console.Write(GetType(T))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC36651: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test1(Of T)(ByRef x As T, y As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
Test1(t, DirectCast(1, ValueType))
~~~~~
</errors>)
End Sub
<Fact>
Public Sub Inference11()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim ab = (a:=1, b:=2)
Dim cd = (c:=1, d:=2)
Test3(ab, cd)
Test1(ab, cd)
Test2(ab, cd)
End Sub
Shared Sub Test1(Of T)(ByRef x As T, y As T)
Console.Write(GetType(T))
End Sub
Shared Sub Test2(Of T)(x As T, ByRef y As T)
Console.Write(GetType(T))
End Sub
Shared Sub Test3(Of T)(ByRef x As T, ByRef y As T)
Console.Write(GetType(T))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim test3 = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().First()
Assert.Equal("Sub C.Test3(Of (System.Int32, System.Int32))(ByRef x As (System.Int32, System.Int32), ByRef y As (System.Int32, System.Int32))",
model.GetSymbolInfo(test3).Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub Inference12()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2)))
End Sub
Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U))
Console.WriteLine(GetType(U))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.Object
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
")
End Sub
<Fact>
<WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")>
Public Sub Inference13()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object)))
Test1(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2)))
End Sub
Shared Function Nullable(Of T as structure)(x as T) as T?
return x
End Function
Shared Sub Test1(Of T, U)(x As (T, U)?, y As (T, U))
Console.WriteLine(GetType(U))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.Object
System.Object
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
")
End Sub
<Fact>
<WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")>
<WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")>
Public Sub Inference13a()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object)))
Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object))))
End Sub
Shared Function Nullable(Of T as structure)(x as T) as T?
return x
End Function
Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))
Console.WriteLine(GetType(U))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
AssertTheseDiagnostics(comp,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object)))
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object))))
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Inference14()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2)))
Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2)))
End Sub
Shared Sub Test1(Of T, U As Structure)(x As (T, U)?, y As (T, U)?)
Console.WriteLine(GetType(U))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.Int32,System.Int32]
")
' In C#, there are errors because names matter during best type inference
' This should get fixed after issue https://github.com/dotnet/roslyn/issues/13938 is fixed
End Sub
<Fact>
Public Sub Inference15()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Test1((a:="1", b:=Nothing), (a:=Nothing, b:="w"), Function(x) x.z)
End Sub
Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U), f As Func(Of (x As T, z As U), T))
Console.WriteLine(GetType(U))
Console.WriteLine(f(y))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.String
w
")
End Sub
<Fact>
Public Sub Inference16()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim x = (1, 2, 3)
Test(x)
Dim x1 = (1, 2, CType(3, Long))
Test(x1)
Dim x2 = (1, DirectCast(2, Object), CType(3, Long))
Test(x2)
End Sub
Shared Sub Test(Of T)(x As (T, T, T))
Console.WriteLine(GetType(T))
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
System.Int32
System.Int64
System.Object
")
End Sub
<Fact()>
Public Sub Constraints_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Structure ValueTuple(Of T1 As Class, T2)
Sub New(_1 As T1, _2 As T2)
End Sub
End Structure
End Namespace
Class C
Sub M(p As (Integer, Integer))
Dim t0 = (1, 2)
Dim t1 As (Integer, Integer) = t0
End Sub
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Sub M(p As (Integer, Integer))
~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Dim t0 = (1, 2)
~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Dim t1 As (Integer, Integer) = t0
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Constraints_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator))
Dim t0 As (Integer, ArgIterator) = p
Dim t1 = (1, New ArgIterator())
Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing)
Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2
End Sub
End Class
]]></file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator))
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator))
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t0 As (Integer, ArgIterator) = p
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t1 = (1, New ArgIterator())
~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing)
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2
~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Constraints_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Namespace System
Public Structure ValueTuple(Of T1, T2 As Class)
Sub New(_1 As T1, _2 As T2)
End Sub
End Structure
End Namespace
Class C(Of T)
Dim field As List(Of (T, T))
Function M(Of U)(x As U) As (U, U)
Dim t0 = New C(Of Integer)()
Dim t1 = M(1)
Return (Nothing, Nothing)
End Function
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC32106: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T2'.
Dim field As List(Of (T, T))
~
BC32106: Type argument 'U' does not satisfy the 'Class' constraint for type parameter 'T2'.
Function M(Of U)(x As U) As (U, U)
~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Constraints_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Namespace System
Public Structure ValueTuple(Of T1, T2 As Class)
Sub New(_1 As T1, _2 As T2)
End Sub
End Structure
End Namespace
Class C(Of T As Class)
Dim field As List(Of (T, T))
Function M(Of U As Class)(x As U) As (U, U)
Dim t0 = New C(Of Integer)()
Dim t1 = M(1)
Return (Nothing, Nothing)
End Function
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim t0 = New C(Of Integer)()
~~~~~~~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'.
Dim t1 = M(1)
~
</errors>)
End Sub
<Fact()>
Public Sub Constraints_05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Namespace System
Public Structure ValueTuple(Of T1, T2 As Structure)
Sub New(_1 As T1, _2 As T2)
End Sub
End Structure
End Namespace
Class C(Of T As Class)
Dim field As List(Of (T, T))
Function M(Of U As Class)(x As (U, U)) As (U, U)
Dim t0 = New C(Of Integer)()
Dim t1 = M((1, 2))
Return (Nothing, Nothing)
End Function
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC32105: Type argument 'T' does not satisfy the 'Structure' constraint for type parameter 'T2'.
Dim field As List(Of (T, T))
~
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'.
Function M(Of U As Class)(x As (U, U)) As (U, U)
~
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'.
Function M(Of U As Class)(x As (U, U)) As (U, U)
~~~~~~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim t0 = New C(Of Integer)()
~~~~~~~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'.
Dim t1 = M((1, 2))
~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T2'.
Return (Nothing, Nothing)
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Constraints_06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Structure ValueTuple(Of T1 As Class)
Public Sub New(item1 As T1)
End Sub
End Structure
Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest As Class)
Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest)
End Sub
End Structure
End Namespace
Class C
Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer))
Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8)
Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0
End Sub
End Class
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer))
~
BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'.
Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer))
~
BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'.
Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8)
~~~~~~~~~~~~~~~~~~~~~~~~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8)
~
BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'.
Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'.
Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub LongTupleConstraints()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator))
Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p
Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator())
Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))()
Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))()
Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3
Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4
End Sub
Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator))
Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q
Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator())
End Sub
End Class]]></file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator))
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator())
~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))()
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))()
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator))
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator())
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub RestrictedTypes1()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim x = (1, 2, New ArgIterator())
Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator())
Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator())
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim x = (1, 2, New ArgIterator())
~~~~~~~~~~~~~~~~~
BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As Object)'.
Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator())
~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator())
~
BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As ArgIterator)'.
Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator())
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub RestrictedTypes2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim y As (x As Integer, y As ArgIterator)
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC42024: Unused local variable: 'y'.
Dim y As (x As Integer, y As ArgIterator)
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim y As (x As Integer, y As ArgIterator)
~
</errors>)
End Sub
<Fact>
Public Sub ImplementInterface()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Interface I
Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String)
ReadOnly Property P1 As (Alice As Integer, Bob As String)
End Interface
Public Class C
Implements I
Shared Sub Main()
Dim c = New C()
Dim x = c.M(c.P1)
Console.Write(x)
End Sub
Public Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String) Implements I.M
Return value
End Function
ReadOnly Property P1 As (Alice As Integer, Bob As String) Implements I.P1
Get
Return (r:=1, s:="hello")
End Get
End Property
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(1, hello)")
End Sub
<Fact>
Public Sub TupleTypeArguments()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Interface I(Of TA, TB As TA)
Function M(a As TA, b As TB) As (TA, TB)
End Interface
Public Class C
Implements I(Of (Integer, String), (Alice As Integer, Bob As String))
Shared Sub Main()
Dim c = New C()
Dim x = c.M((1, "Australia"), (2, "Brazil"))
Console.Write(x)
End Sub
Public Function M(x As (Integer, String), y As (Alice As Integer, Bob As String)) As ((Integer, String), (Alice As Integer, Bob As String)) Implements I(Of (Integer, String), (Alice As Integer, Bob As String)).M
Return (x, y)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="((1, Australia), (2, Brazil))")
End Sub
<Fact>
Public Sub OverrideGenericInterfaceWithDifferentNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Interface I(Of TA, TB As TA)
Function M(paramA As TA, paramB As TB) As (returnA As TA, returnB As TB)
End Interface
Public Class C
Implements I(Of (a As Integer, b As String), (Integer, String))
Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M
Throw New Exception()
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30149: Class 'C' must implement 'Function M(paramA As (a As Integer, b As String), paramB As (Integer, String)) As (returnA As (a As Integer, b As String), returnB As (Integer, String))' for interface 'I(Of (a As Integer, b As String), (Integer, String))'.
Implements I(Of (a As Integer, b As String), (Integer, String))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31035: Interface 'I(Of (b As Integer, a As Integer), (a As Integer, b As Integer))' is not implemented by this class.
Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub TupleWithoutFeatureFlag()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim x As (Integer, Integer) = (1, 1)
Else
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic14))
comp.AssertTheseDiagnostics(
<errors>
BC36716: Visual Basic 14.0 does not support tuples.
Dim x As (Integer, Integer) = (1, 1)
~~~~~~~~~~~~~~~~~~
BC36716: Visual Basic 14.0 does not support tuples.
Dim x As (Integer, Integer) = (1, 1)
~~~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
Else
~~~~
</errors>)
Dim x = comp.GetDiagnostics()
Assert.Equal("15", Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(0)))
Assert.Null(Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(2)))
Assert.Throws(Of ArgumentNullException)(Sub() Compilation.GetRequiredLanguageVersion(Nothing))
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v1 = M1()
Console.WriteLine($"{v1.Item1} {v1.Item2}")
Dim v2 = M2()
Console.WriteLine($"{v2.Item1} {v2.Item2} {v2.a2} {v2.b2}")
Dim v6 = M6()
Console.WriteLine($"{v6.Item1} {v6.Item2} {v6.item1} {v6.item2}")
Console.WriteLine(v1.ToString())
Console.WriteLine(v2.ToString())
Console.WriteLine(v6.ToString())
End Sub
Shared Function M1() As (Integer, Integer)
Return (1, 11)
End Function
Shared Function M2() As (a2 As Integer, b2 As Integer)
Return (2, 22)
End Function
Shared Function M6() As (item1 As Integer, item2 As Integer)
Return (6, 66)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
1 11
2 22 2 22
6 66 6 66
(1, 11)
(2, 22)
(6, 66)
")
Dim c = comp.GetTypeByMetadataName("C")
Dim m1Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M1").ReturnType, NamedTypeSymbol)
Dim m2Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M2").ReturnType, NamedTypeSymbol)
Dim m6Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M6").ReturnType, NamedTypeSymbol)
AssertTestDisplayString(m1Tuple.GetMembers(),
"(System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32).Item2 As System.Int32",
"Sub (System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32"
)
Assert.Equal({
".ctor",
".ctor",
"CompareTo",
"Equals",
"Equals",
"GetHashCode",
"Item1",
"Item2",
"System.Collections.IStructuralComparable.CompareTo",
"System.Collections.IStructuralEquatable.Equals",
"System.Collections.IStructuralEquatable.GetHashCode",
"System.IComparable.CompareTo",
"System.ITupleInternal.get_Size",
"System.ITupleInternal.GetHashCode",
"System.ITupleInternal.Size",
"System.ITupleInternal.ToStringEnd",
"ToString"},
DirectCast(m1Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray()
)
AssertTestDisplayString(m2Tuple.GetMembers(),
"(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32",
"Sub (a2 As System.Int32, b2 As System.Int32)..ctor()",
"Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (a2 As System.Int32, b2 As System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (a2 As System.Int32, b2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean",
"Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (a2 As System.Int32, b2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).GetHashCode() As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String",
"Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.Size As System.Int32"
)
Assert.Equal({
".ctor",
".ctor",
"CompareTo",
"Equals",
"Equals",
"GetHashCode",
"Item1",
"Item2",
"System.Collections.IStructuralComparable.CompareTo",
"System.Collections.IStructuralEquatable.Equals",
"System.Collections.IStructuralEquatable.GetHashCode",
"System.IComparable.CompareTo",
"System.ITupleInternal.get_Size",
"System.ITupleInternal.GetHashCode",
"System.ITupleInternal.Size",
"System.ITupleInternal.ToStringEnd",
"ToString"},
DirectCast(m2Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray()
)
AssertTestDisplayString(m6Tuple.GetMembers(),
"(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32",
"Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()",
"Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (Item1 As System.Int32, Item2 As System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).GetHashCode() As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.Size As System.Int32"
)
Assert.Equal({
".ctor",
".ctor",
"CompareTo",
"Equals",
"Equals",
"GetHashCode",
"Item1",
"Item2",
"System.Collections.IStructuralComparable.CompareTo",
"System.Collections.IStructuralEquatable.Equals",
"System.Collections.IStructuralEquatable.GetHashCode",
"System.IComparable.CompareTo",
"System.ITupleInternal.get_Size",
"System.ITupleInternal.GetHashCode",
"System.ITupleInternal.Size",
"System.ITupleInternal.ToStringEnd",
"ToString"},
DirectCast(m6Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray()
)
Assert.Equal("", m1Tuple.Name)
Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind)
Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind)
Assert.False(m1Tuple.IsImplicitlyDeclared)
Assert.True(m1Tuple.IsTupleType)
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString())
Assert.Same(m1Tuple, m1Tuple.ConstructedFrom)
Assert.Same(m1Tuple, m1Tuple.OriginalDefinition)
AssertTupleTypeEquality(m1Tuple)
Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol)
Assert.Null(m1Tuple.EnumUnderlyingType)
Assert.Equal({
"Item1",
"Item2",
".ctor",
"Equals",
"System.Collections.IStructuralEquatable.Equals",
"System.IComparable.CompareTo",
"CompareTo",
"System.Collections.IStructuralComparable.CompareTo",
"GetHashCode",
"System.Collections.IStructuralEquatable.GetHashCode",
"System.ITupleInternal.GetHashCode",
"ToString",
"System.ITupleInternal.ToStringEnd",
"System.ITupleInternal.get_Size",
"System.ITupleInternal.Size"},
m1Tuple.MemberNames.ToArray())
Assert.Equal({
"Item1",
"a2",
"Item2",
"b2",
".ctor",
"Equals",
"System.Collections.IStructuralEquatable.Equals",
"System.IComparable.CompareTo",
"CompareTo",
"System.Collections.IStructuralComparable.CompareTo",
"GetHashCode",
"System.Collections.IStructuralEquatable.GetHashCode",
"System.ITupleInternal.GetHashCode",
"ToString",
"System.ITupleInternal.ToStringEnd",
"System.ITupleInternal.get_Size",
"System.ITupleInternal.Size"},
m2Tuple.MemberNames.ToArray())
Assert.Equal(0, m1Tuple.Arity)
Assert.True(m1Tuple.TypeParameters.IsEmpty)
Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString())
Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers)
Assert.False(m1Tuple.IsComImport)
Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty)
Assert.True(m1Tuple.GetAttributes().IsEmpty)
Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString())
Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString())
Assert.True(m1Tuple.GetTypeMembers().IsEmpty)
Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty)
Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty)
Assert.Equal(6, m1Tuple.Interfaces.Length)
Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty)
Assert.Equal(1, m1Tuple.Locations.Length)
Assert.Equal("(Integer, Integer)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("(a2 As Integer, b2 As Integer)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
AssertTupleTypeEquality(m2Tuple)
AssertTupleTypeEquality(m6Tuple)
Assert.False(m1Tuple.Equals(m2Tuple))
Assert.False(m1Tuple.Equals(m6Tuple))
Assert.False(m6Tuple.Equals(m2Tuple))
AssertTupleTypeMembersEquality(m1Tuple, m2Tuple)
AssertTupleTypeMembersEquality(m1Tuple, m6Tuple)
AssertTupleTypeMembersEquality(m2Tuple, m6Tuple)
Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(0), FieldSymbol)
Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(0), FieldSymbol)
Dim m2a2 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol)
AssertNonvirtualTupleElementField(m1Item1)
AssertNonvirtualTupleElementField(m2Item1)
AssertVirtualTupleElementField(m2a2)
Assert.True(m1Item1.IsTupleField)
Assert.Same(m1Item1, m1Item1.OriginalDefinition)
Assert.True(m1Item1.Equals(m1Item1))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m1Item1.AssociatedSymbol)
Assert.Same(m1Tuple, m1Item1.ContainingSymbol)
Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol)
Assert.True(m1Item1.CustomModifiers.IsEmpty)
Assert.True(m1Item1.GetAttributes().IsEmpty)
Assert.Null(m1Item1.GetUseSiteErrorInfo())
Assert.False(m1Item1.Locations.IsEmpty)
Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty)
Assert.Equal("Item1", m1Item1.TupleUnderlyingField.Name)
Assert.True(m1Item1.IsImplicitlyDeclared)
Assert.Null(m1Item1.TypeLayoutOffset)
Assert.True(m2Item1.IsTupleField)
Assert.Same(m2Item1, m2Item1.OriginalDefinition)
Assert.True(m2Item1.Equals(m2Item1))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m2Item1.AssociatedSymbol)
Assert.Same(m2Tuple, m2Item1.ContainingSymbol)
Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol)
Assert.True(m2Item1.CustomModifiers.IsEmpty)
Assert.True(m2Item1.GetAttributes().IsEmpty)
Assert.Null(m2Item1.GetUseSiteErrorInfo())
Assert.False(m2Item1.Locations.IsEmpty)
Assert.Equal("Item1", m2Item1.Name)
Assert.Equal("Item1", m2Item1.TupleUnderlyingField.Name)
Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single())
Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item1.TupleUnderlyingField.Locations.Single().ToString())
Assert.Equal("SourceFile(a.vb[589..591))", m2Item1.Locations.Single().ToString())
Assert.True(m2Item1.IsImplicitlyDeclared)
Assert.Null(m2Item1.TypeLayoutOffset)
Assert.True(m2a2.IsTupleField)
Assert.Same(m2a2, m2a2.OriginalDefinition)
Assert.True(m2a2.Equals(m2a2))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m2a2.AssociatedSymbol)
Assert.Same(m2Tuple, m2a2.ContainingSymbol)
Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol)
Assert.True(m2a2.CustomModifiers.IsEmpty)
Assert.True(m2a2.GetAttributes().IsEmpty)
Assert.Null(m2a2.GetUseSiteErrorInfo())
Assert.False(m2a2.Locations.IsEmpty)
Assert.Equal("a2 As Integer", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("Item1", m2a2.TupleUnderlyingField.Name)
Assert.False(m2a2.IsImplicitlyDeclared)
Assert.Null(m2a2.TypeLayoutOffset)
End Sub
Private Sub AssertTupleTypeEquality(tuple As NamedTypeSymbol)
Assert.True(tuple.Equals(tuple))
Dim members = tuple.GetMembers()
For i = 0 To members.Length - 1
For j = 0 To members.Length - 1
If i <> j Then
Assert.NotSame(members(i), members(j))
Assert.False(members(i).Equals(members(j)))
Assert.False(members(j).Equals(members(i)))
End If
Next
Next
Dim underlyingMembers = tuple.TupleUnderlyingType.GetMembers()
For Each m In members
Assert.False(underlyingMembers.Any(Function(u) u.Equals(m)))
Assert.False(underlyingMembers.Any(Function(u) m.Equals(u)))
Next
End Sub
Private Sub AssertTupleTypeMembersEquality(tuple1 As NamedTypeSymbol, tuple2 As NamedTypeSymbol)
Assert.NotSame(tuple1, tuple2)
If tuple1.Equals(tuple2) Then
Assert.True(tuple2.Equals(tuple1))
Dim members1 = tuple1.GetMembers()
Dim members2 = tuple2.GetMembers()
Assert.Equal(members1.Length, members2.Length)
For i = 0 To members1.Length - 1
Assert.NotSame(members1(i), members2(i))
Assert.True(members1(i).Equals(members2(i)))
Assert.True(members2(i).Equals(members1(i)))
Assert.Equal(members2(i).GetHashCode(), members1(i).GetHashCode())
If members1(i).Kind = SymbolKind.Method Then
Dim parameters1 = DirectCast(members1(i), MethodSymbol).Parameters
Dim parameters2 = DirectCast(members2(i), MethodSymbol).Parameters
AssertTupleMembersParametersEquality(parameters1, parameters2)
Dim typeParameters1 = DirectCast(members1(i), MethodSymbol).TypeParameters
Dim typeParameters2 = DirectCast(members2(i), MethodSymbol).TypeParameters
Assert.Equal(typeParameters1.Length, typeParameters2.Length)
For j = 0 To typeParameters1.Length - 1
Assert.NotSame(typeParameters1(j), typeParameters2(j))
Assert.True(typeParameters1(j).Equals(typeParameters2(j)))
Assert.True(typeParameters2(j).Equals(typeParameters1(j)))
Assert.Equal(typeParameters2(j).GetHashCode(), typeParameters1(j).GetHashCode())
Next
ElseIf members1(i).Kind = SymbolKind.Property Then
Dim parameters1 = DirectCast(members1(i), PropertySymbol).Parameters
Dim parameters2 = DirectCast(members2(i), PropertySymbol).Parameters
AssertTupleMembersParametersEquality(parameters1, parameters2)
End If
Next
For i = 0 To members1.Length - 1
For j = 0 To members2.Length - 1
If i <> j Then
Assert.NotSame(members1(i), members2(j))
Assert.False(members1(i).Equals(members2(j)))
End If
Next
Next
Else
Assert.False(tuple2.Equals(tuple1))
Dim members1 = tuple1.GetMembers()
Dim members2 = tuple2.GetMembers()
For Each m In members1
Assert.False(members2.Any(Function(u) u.Equals(m)))
Assert.False(members2.Any(Function(u) m.Equals(u)))
Next
End If
End Sub
Private Sub AssertTupleMembersParametersEquality(parameters1 As ImmutableArray(Of ParameterSymbol), parameters2 As ImmutableArray(Of ParameterSymbol))
Assert.Equal(parameters1.Length, parameters2.Length)
For j = 0 To parameters1.Length - 1
Assert.NotSame(parameters1(j), parameters2(j))
Assert.True(parameters1(j).Equals(parameters2(j)))
Assert.True(parameters2(j).Equals(parameters1(j)))
Assert.Equal(parameters2(j).GetHashCode(), parameters1(j).GetHashCode())
Next
End Sub
Private Sub AssertVirtualTupleElementField(sym As FieldSymbol)
Assert.True(sym.IsTupleField)
Assert.True(sym.IsVirtualTupleField)
' it is an element so must have nonnegative index
Assert.True(sym.TupleElementIndex >= 0)
End Sub
Private Sub AssertNonvirtualTupleElementField(sym As FieldSymbol)
Assert.True(sym.IsTupleField)
Assert.False(sym.IsVirtualTupleField)
' it is an element so must have nonnegative index
Assert.True(sym.TupleElementIndex >= 0)
' if it was 8th or after, it would be virtual
Assert.True(sym.TupleElementIndex < TupleTypeSymbol.RestPosition - 1)
End Sub
Private Shared Sub AssertTestDisplayString(symbols As ImmutableArray(Of Symbol), ParamArray baseLine As String())
' Re-ordering arguments because expected is usually first.
AssertEx.Equal(baseLine, symbols.Select(Function(s) s.ToTestDisplayString()))
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v3 = M3()
Console.WriteLine(v3.Item1)
Console.WriteLine(v3.Item2)
Console.WriteLine(v3.Item3)
Console.WriteLine(v3.Item4)
Console.WriteLine(v3.Item5)
Console.WriteLine(v3.Item6)
Console.WriteLine(v3.Item7)
Console.WriteLine(v3.Item8)
Console.WriteLine(v3.Item9)
Console.WriteLine(v3.Rest.Item1)
Console.WriteLine(v3.Rest.Item2)
Console.WriteLine(v3.ToString())
End Sub
Shared Function M3() As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)
Return (31, 32, 33, 34, 35, 36, 37, 38, 39)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
31
32
33
34
35
36
37
38
39
38
39
(31, 32, 33, 34, 35, 36, 37, 38, 39)
")
Dim c = comp.GetTypeByMetadataName("C")
Dim m3Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M3").ReturnType, NamedTypeSymbol)
AssertTestDisplayString(m3Tuple.GetMembers(),
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32"
)
Dim m3Item8 = DirectCast(m3Tuple.GetMembers("Item8").Single(), FieldSymbol)
AssertVirtualTupleElementField(m3Item8)
Assert.True(m3Item8.IsTupleField)
Assert.Same(m3Item8, m3Item8.OriginalDefinition)
Assert.True(m3Item8.Equals(m3Item8))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m3Item8.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m3Item8.AssociatedSymbol)
Assert.Same(m3Tuple, m3Item8.ContainingSymbol)
Assert.NotEqual(m3Tuple.TupleUnderlyingType, m3Item8.TupleUnderlyingField.ContainingSymbol)
Assert.True(m3Item8.CustomModifiers.IsEmpty)
Assert.True(m3Item8.GetAttributes().IsEmpty)
Assert.Null(m3Item8.GetUseSiteErrorInfo())
Assert.False(m3Item8.Locations.IsEmpty)
Assert.True(m3Item8.DeclaringSyntaxReferences.IsEmpty)
Assert.Equal("Item1", m3Item8.TupleUnderlyingField.Name)
Assert.True(m3Item8.IsImplicitlyDeclared)
Assert.Null(m3Item8.TypeLayoutOffset)
Dim m3TupleRestTuple = DirectCast(DirectCast(m3Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol)
AssertTestDisplayString(m3TupleRestTuple.GetMembers(),
"(System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32).Item2 As System.Int32",
"Sub (System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32"
)
Assert.True(m3TupleRestTuple.IsTupleType)
AssertTupleTypeEquality(m3TupleRestTuple)
Assert.True(m3TupleRestTuple.Locations.IsEmpty)
Assert.True(m3TupleRestTuple.DeclaringSyntaxReferences.IsEmpty)
For Each m In m3TupleRestTuple.GetMembers().OfType(Of FieldSymbol)()
Assert.True(m.Locations.IsEmpty)
Next
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v4 = M4()
Console.WriteLine(v4.Item1)
Console.WriteLine(v4.Item2)
Console.WriteLine(v4.Item3)
Console.WriteLine(v4.Item4)
Console.WriteLine(v4.Item5)
Console.WriteLine(v4.Item6)
Console.WriteLine(v4.Item7)
Console.WriteLine(v4.Item8)
Console.WriteLine(v4.Item9)
Console.WriteLine(v4.Rest.Item1)
Console.WriteLine(v4.Rest.Item2)
Console.WriteLine(v4.a4)
Console.WriteLine(v4.b4)
Console.WriteLine(v4.c4)
Console.WriteLine(v4.d4)
Console.WriteLine(v4.e4)
Console.WriteLine(v4.f4)
Console.WriteLine(v4.g4)
Console.WriteLine(v4.h4)
Console.WriteLine(v4.i4)
Console.WriteLine(v4.ToString())
End Sub
Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer)
Return (41, 42, 43, 44, 45, 46, 47, 48, 49)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
41
42
43
44
45
46
47
48
49
48
49
41
42
43
44
45
46
47
48
49
(41, 42, 43, 44, 45, 46, 47, 48, 49)
")
Dim c = comp.GetTypeByMetadataName("C")
Dim m4Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M4").ReturnType, NamedTypeSymbol)
AssertTupleTypeEquality(m4Tuple)
AssertTestDisplayString(m4Tuple.GetMembers(),
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item1 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).a4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item2 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).b4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item3 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).c4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).d4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item5 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).e4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item6 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).f4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item7 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).g4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Rest As (System.Int32, System.Int32)",
"Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor()",
"Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).GetHashCode() As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).ToString() As System.String",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.Size As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item8 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).h4 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item9 As System.Int32",
"(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).i4 As System.Int32"
)
Dim m4Item8 = DirectCast(m4Tuple.GetMembers("Item8").Single(), FieldSymbol)
AssertVirtualTupleElementField(m4Item8)
Assert.True(m4Item8.IsTupleField)
Assert.Same(m4Item8, m4Item8.OriginalDefinition)
Assert.True(m4Item8.Equals(m4Item8))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4Item8.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m4Item8.AssociatedSymbol)
Assert.Same(m4Tuple, m4Item8.ContainingSymbol)
Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4Item8.TupleUnderlyingField.ContainingSymbol)
Assert.True(m4Item8.CustomModifiers.IsEmpty)
Assert.True(m4Item8.GetAttributes().IsEmpty)
Assert.Null(m4Item8.GetUseSiteErrorInfo())
Assert.False(m4Item8.Locations.IsEmpty)
Assert.Equal("Item1", m4Item8.TupleUnderlyingField.Name)
Assert.True(m4Item8.IsImplicitlyDeclared)
Assert.Null(m4Item8.TypeLayoutOffset)
Dim m4h4 = DirectCast(m4Tuple.GetMembers("h4").Single(), FieldSymbol)
AssertVirtualTupleElementField(m4h4)
Assert.True(m4h4.IsTupleField)
Assert.Same(m4h4, m4h4.OriginalDefinition)
Assert.True(m4h4.Equals(m4h4))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4h4.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m4h4.AssociatedSymbol)
Assert.Same(m4Tuple, m4h4.ContainingSymbol)
Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4h4.TupleUnderlyingField.ContainingSymbol)
Assert.True(m4h4.CustomModifiers.IsEmpty)
Assert.True(m4h4.GetAttributes().IsEmpty)
Assert.Null(m4h4.GetUseSiteErrorInfo())
Assert.False(m4h4.Locations.IsEmpty)
Assert.Equal("Item1", m4h4.TupleUnderlyingField.Name)
Assert.False(m4h4.IsImplicitlyDeclared)
Assert.Null(m4h4.TypeLayoutOffset)
Dim m4TupleRestTuple = DirectCast(DirectCast(m4Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol)
AssertTestDisplayString(m4TupleRestTuple.GetMembers(),
"(System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32).Item2 As System.Int32",
"Sub (System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32"
)
For Each m In m4TupleRestTuple.GetMembers().OfType(Of FieldSymbol)()
Assert.True(m.Locations.IsEmpty)
Next
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v4 = M4()
Console.WriteLine(v4.Rest.a4)
Console.WriteLine(v4.Rest.b4)
Console.WriteLine(v4.Rest.c4)
Console.WriteLine(v4.Rest.d4)
Console.WriteLine(v4.Rest.e4)
Console.WriteLine(v4.Rest.f4)
Console.WriteLine(v4.Rest.g4)
Console.WriteLine(v4.Rest.h4)
Console.WriteLine(v4.Rest.i4)
Console.WriteLine(v4.ToString())
End Sub
Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer)
Return (41, 42, 43, 44, 45, 46, 47, 48, 49)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30456: 'a4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.a4)
~~~~~~~~~~
BC30456: 'b4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.b4)
~~~~~~~~~~
BC30456: 'c4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.c4)
~~~~~~~~~~
BC30456: 'd4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.d4)
~~~~~~~~~~
BC30456: 'e4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.e4)
~~~~~~~~~~
BC30456: 'f4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.f4)
~~~~~~~~~~
BC30456: 'g4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.g4)
~~~~~~~~~~
BC30456: 'h4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.h4)
~~~~~~~~~~
BC30456: 'i4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v4.Rest.i4)
~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v5 = M5()
Console.WriteLine(v5.Item1)
Console.WriteLine(v5.Item2)
Console.WriteLine(v5.Item3)
Console.WriteLine(v5.Item4)
Console.WriteLine(v5.Item5)
Console.WriteLine(v5.Item6)
Console.WriteLine(v5.Item7)
Console.WriteLine(v5.Item8)
Console.WriteLine(v5.Item9)
Console.WriteLine(v5.Item10)
Console.WriteLine(v5.Item11)
Console.WriteLine(v5.Item12)
Console.WriteLine(v5.Item13)
Console.WriteLine(v5.Item14)
Console.WriteLine(v5.Item15)
Console.WriteLine(v5.Item16)
Console.WriteLine(v5.Rest.Item1)
Console.WriteLine(v5.Rest.Item2)
Console.WriteLine(v5.Rest.Item3)
Console.WriteLine(v5.Rest.Item4)
Console.WriteLine(v5.Rest.Item5)
Console.WriteLine(v5.Rest.Item6)
Console.WriteLine(v5.Rest.Item7)
Console.WriteLine(v5.Rest.Item8)
Console.WriteLine(v5.Rest.Item9)
Console.WriteLine(v5.Rest.Rest.Item1)
Console.WriteLine(v5.Rest.Rest.Item2)
Console.WriteLine(v5.ToString())
End Sub
Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer,
Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer)
Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
508
509
510
511
512
513
514
515
516
515
516
(501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516)
")
Dim c = comp.GetTypeByMetadataName("C")
Dim m5Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M5").ReturnType, NamedTypeSymbol)
AssertTupleTypeEquality(m5Tuple)
AssertTestDisplayString(m5Tuple.GetMembers(),
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item1 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item2 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item3 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item4 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item5 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item6 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item7 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)",
"Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor()",
"Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).GetHashCode() As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).ToString() As System.String",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.Size As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item8 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item9 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item10 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item11 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item12 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item13 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item14 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item15 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item16 As System.Int32"
)
Dim m5Item8 = DirectCast(m5Tuple.GetMembers("Item8").Single(), FieldSymbol)
AssertVirtualTupleElementField(m5Item8)
Assert.True(m5Item8.IsTupleField)
Assert.Same(m5Item8, m5Item8.OriginalDefinition)
Assert.True(m5Item8.Equals(m5Item8))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32)).Item1 As System.Int32", m5Item8.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m5Item8.AssociatedSymbol)
Assert.Same(m5Tuple, m5Item8.ContainingSymbol)
Assert.NotEqual(m5Tuple.TupleUnderlyingType, m5Item8.TupleUnderlyingField.ContainingSymbol)
Assert.True(m5Item8.CustomModifiers.IsEmpty)
Assert.True(m5Item8.GetAttributes().IsEmpty)
Assert.Null(m5Item8.GetUseSiteErrorInfo())
Assert.False(m5Item8.Locations.IsEmpty)
Assert.Equal("Item8 As Integer", m5Item8.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("Item1", m5Item8.TupleUnderlyingField.Name)
Assert.False(m5Item8.IsImplicitlyDeclared)
Assert.Null(m5Item8.TypeLayoutOffset)
Dim m5TupleRestTuple = DirectCast(DirectCast(m5Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol)
AssertVirtualTupleElementField(m5Item8)
AssertTestDisplayString(m5TupleRestTuple.GetMembers(),
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32"
)
For Each m In m5TupleRestTuple.GetMembers().OfType(Of FieldSymbol)()
If m.Name <> "Rest" Then
Assert.True(m.Locations.IsEmpty)
Else
Assert.Equal("Rest", m.Name)
End If
Next
Dim m5TupleRestTupleRestTuple = DirectCast(DirectCast(m5TupleRestTuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol)
AssertTupleTypeEquality(m5TupleRestTupleRestTuple)
AssertTestDisplayString(m5TupleRestTuple.GetMembers(),
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()",
"Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32",
"(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32"
)
For Each m In m5TupleRestTupleRestTuple.GetMembers().OfType(Of FieldSymbol)()
Assert.True(m.Locations.IsEmpty)
Next
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v5 = M5()
Console.WriteLine(v5.Rest.Item10)
Console.WriteLine(v5.Rest.Item11)
Console.WriteLine(v5.Rest.Item12)
Console.WriteLine(v5.Rest.Item13)
Console.WriteLine(v5.Rest.Item14)
Console.WriteLine(v5.Rest.Item15)
Console.WriteLine(v5.Rest.Item16)
Console.WriteLine(v5.Rest.Rest.Item3)
Console.WriteLine(v5.Rest.Rest.Item4)
Console.WriteLine(v5.Rest.Rest.Item5)
Console.WriteLine(v5.Rest.Rest.Item6)
Console.WriteLine(v5.Rest.Rest.Item7)
Console.WriteLine(v5.Rest.Rest.Item8)
Console.WriteLine(v5.Rest.Rest.Item9)
Console.WriteLine(v5.Rest.Rest.Item10)
Console.WriteLine(v5.Rest.Rest.Item11)
Console.WriteLine(v5.Rest.Rest.Item12)
Console.WriteLine(v5.Rest.Rest.Item13)
Console.WriteLine(v5.Rest.Rest.Item14)
Console.WriteLine(v5.Rest.Rest.Item15)
Console.WriteLine(v5.Rest.Rest.Item16)
End Sub
Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer,
Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer)
Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30456: 'Item10' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item10)
~~~~~~~~~~~~~~
BC30456: 'Item11' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item11)
~~~~~~~~~~~~~~
BC30456: 'Item12' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item12)
~~~~~~~~~~~~~~
BC30456: 'Item13' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item13)
~~~~~~~~~~~~~~
BC30456: 'Item14' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item14)
~~~~~~~~~~~~~~
BC30456: 'Item15' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item15)
~~~~~~~~~~~~~~
BC30456: 'Item16' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'.
Console.WriteLine(v5.Rest.Item16)
~~~~~~~~~~~~~~
BC30456: 'Item3' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item3)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item4' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item4)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item5' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item5)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item6' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item6)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item7' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item7)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item8' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item8)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item9' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item9)
~~~~~~~~~~~~~~~~~~
BC30456: 'Item10' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item10)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item11' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item11)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item12' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item12)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item13' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item13)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item14' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item14)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item15' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item15)
~~~~~~~~~~~~~~~~~~~
BC30456: 'Item16' is not a member of '(Integer, Integer)'.
Console.WriteLine(v5.Rest.Rest.Item16)
~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_07()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
End Sub
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
Return (701, 702, 703, 704, 705, 706, 707, 708, 709)
End Function
End Class
<%= s_trivial2uple %><%= s_trivial3uple %><%= s_trivialRemainingTuples %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(
<errors>
BC37261: Tuple element name 'Item9' is only allowed at position 9.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item1' is only allowed at position 1.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item2' is only allowed at position 2.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item3' is only allowed at position 3.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item4' is only allowed at position 4.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item5' is only allowed at position 5.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item6' is only allowed at position 6.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item7' is only allowed at position 7.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
BC37261: Tuple element name 'Item8' is only allowed at position 8.
Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer)
~~~~~
</errors>)
Dim c = comp.GetTypeByMetadataName("C")
Dim m7Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M7").ReturnType, NamedTypeSymbol)
AssertTupleTypeEquality(m7Tuple)
AssertTestDisplayString(m7Tuple.GetMembers(),
"Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor()",
"Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32",
"(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32"
)
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_08()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
End Sub
Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer)
Return (801, 802, 803, 804, 805, 806, 807, 808)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37261: Tuple element name 'Item1' is only allowed at position 1.
Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer)
~~~~~
</errors>)
Dim c = comp.GetTypeByMetadataName("C")
Dim m8Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M8").ReturnType, NamedTypeSymbol)
AssertTupleTypeEquality(m8Tuple)
AssertTestDisplayString(m8Tuple.GetMembers(),
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a1 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item2 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a2 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item3 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a3 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item4 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a4 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item5 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a5 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item6 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a6 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item7 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a7 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Rest As ValueTuple(Of System.Int32)",
"Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor()",
"Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As ValueTuple(Of System.Int32))",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Boolean",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).GetHashCode() As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).ToString() As System.String",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.Size As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item8 As System.Int32",
"(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32"
)
Dim m8Item8 = DirectCast(m8Tuple.GetMembers("Item8").Single(), FieldSymbol)
AssertVirtualTupleElementField(m8Item8)
Assert.True(m8Item8.IsTupleField)
Assert.Same(m8Item8, m8Item8.OriginalDefinition)
Assert.True(m8Item8.Equals(m8Item8))
Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item8.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m8Item8.AssociatedSymbol)
Assert.Same(m8Tuple, m8Item8.ContainingSymbol)
Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item8.TupleUnderlyingField.ContainingSymbol)
Assert.True(m8Item8.CustomModifiers.IsEmpty)
Assert.True(m8Item8.GetAttributes().IsEmpty)
Assert.Null(m8Item8.GetUseSiteErrorInfo())
Assert.False(m8Item8.Locations.IsEmpty)
Assert.Equal("Item1", m8Item8.TupleUnderlyingField.Name)
Assert.True(m8Item8.IsImplicitlyDeclared)
Assert.Null(m8Item8.TypeLayoutOffset)
Dim m8Item1 = DirectCast(m8Tuple.GetMembers("Item1").Last(), FieldSymbol)
AssertVirtualTupleElementField(m8Item1)
Assert.True(m8Item1.IsTupleField)
Assert.Same(m8Item1, m8Item1.OriginalDefinition)
Assert.True(m8Item1.Equals(m8Item1))
Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item1.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m8Item1.AssociatedSymbol)
Assert.Same(m8Tuple, m8Item1.ContainingSymbol)
Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item1.TupleUnderlyingField.ContainingSymbol)
Assert.True(m8Item1.CustomModifiers.IsEmpty)
Assert.True(m8Item1.GetAttributes().IsEmpty)
Assert.Null(m8Item1.GetUseSiteErrorInfo())
Assert.False(m8Item1.Locations.IsEmpty)
Assert.Equal("Item1", m8Item1.TupleUnderlyingField.Name)
Assert.False(m8Item1.IsImplicitlyDeclared)
Assert.Null(m8Item1.TypeLayoutOffset)
Dim m8TupleRestTuple = DirectCast(DirectCast(m8Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol)
AssertTupleTypeEquality(m8TupleRestTuple)
AssertTestDisplayString(m8TupleRestTuple.GetMembers(),
"ValueTuple(Of System.Int32).Item1 As System.Int32",
"Sub ValueTuple(Of System.Int32)..ctor()",
"Sub ValueTuple(Of System.Int32)..ctor(item1 As System.Int32)",
"Function ValueTuple(Of System.Int32).Equals(obj As System.Object) As System.Boolean",
"Function ValueTuple(Of System.Int32).Equals(other As ValueTuple(Of System.Int32)) As System.Boolean",
"Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean",
"Function ValueTuple(Of System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32",
"Function ValueTuple(Of System.Int32).CompareTo(other As ValueTuple(Of System.Int32)) As System.Int32",
"Function ValueTuple(Of System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32",
"Function ValueTuple(Of System.Int32).GetHashCode() As System.Int32",
"Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function ValueTuple(Of System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32",
"Function ValueTuple(Of System.Int32).ToString() As System.String",
"Function ValueTuple(Of System.Int32).System.ITupleInternal.ToStringEnd() As System.String",
"Function ValueTuple(Of System.Int32).System.ITupleInternal.get_Size() As System.Int32",
"ReadOnly Property ValueTuple(Of System.Int32).System.ITupleInternal.Size As System.Int32"
)
End Sub
<Fact>
Public Sub DefaultAndFriendlyElementNames_09()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Shared Sub Main()
Dim v1 = (1, 11)
Console.WriteLine(v1.Item1)
Console.WriteLine(v1.Item2)
Dim v2 = (a2:=2, b2:=22)
Console.WriteLine(v2.Item1)
Console.WriteLine(v2.Item2)
Console.WriteLine(v2.a2)
Console.WriteLine(v2.b2)
Dim v6 = (item1:=6, item2:=66)
Console.WriteLine(v6.Item1)
Console.WriteLine(v6.Item2)
Console.WriteLine(v6.item1)
Console.WriteLine(v6.item2)
Console.WriteLine(v1.ToString())
Console.WriteLine(v2.ToString())
Console.WriteLine(v6.ToString())
End Sub
End Class
<%= s_trivial2uple %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
CompileAndVerify(comp, expectedOutput:="
1
11
2
22
2
22
6
66
6
66
{1, 11}
{2, 22}
{6, 66}
")
Dim c = comp.GetTypeByMetadataName("C")
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().First()
Dim m1Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v1").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol)
Dim m2Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v2").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol)
Dim m6Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v6").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol)
AssertTestDisplayString(m1Tuple.GetMembers(),
"Sub (System.Int32, System.Int32)..ctor()",
"(System.Int32, System.Int32).Item1 As System.Int32",
"(System.Int32, System.Int32).Item2 As System.Int32",
"Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (System.Int32, System.Int32).ToString() As System.String"
)
AssertTestDisplayString(m2Tuple.GetMembers(),
"Sub (a2 As System.Int32, b2 As System.Int32)..ctor()",
"(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32",
"(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32",
"Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String"
)
AssertTestDisplayString(m6Tuple.GetMembers(),
"Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()",
"(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32",
"(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32",
"Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)",
"Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String"
)
Assert.Equal("", m1Tuple.Name)
Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind)
Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind)
Assert.False(m1Tuple.IsImplicitlyDeclared)
Assert.True(m1Tuple.IsTupleType)
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString())
Assert.Same(m1Tuple, m1Tuple.ConstructedFrom)
Assert.Same(m1Tuple, m1Tuple.OriginalDefinition)
AssertTupleTypeEquality(m1Tuple)
Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol)
Assert.Null(m1Tuple.GetUseSiteErrorInfo())
Assert.Null(m1Tuple.EnumUnderlyingType)
Assert.Equal({".ctor", "Item1", "Item2", "ToString"},
m1Tuple.MemberNames.ToArray())
Assert.Equal({".ctor", "Item1", "a2", "Item2", "b2", "ToString"},
m2Tuple.MemberNames.ToArray())
Assert.Equal(0, m1Tuple.Arity)
Assert.True(m1Tuple.TypeParameters.IsEmpty)
Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString())
Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers)
Assert.False(m1Tuple.IsComImport)
Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty)
Assert.True(m1Tuple.GetAttributes().IsEmpty)
Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString())
Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString())
Assert.True(m1Tuple.GetTypeMembers().IsEmpty)
Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty)
Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty)
Assert.True(m1Tuple.Interfaces.IsEmpty)
Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty)
Assert.Equal(1, m1Tuple.Locations.Length)
Assert.Equal("(1, 11)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("(a2:=2, b2:=22)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("Public Structure ValueTuple(Of T1, T2)", m1Tuple.TupleUnderlyingType.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 38))
AssertTupleTypeEquality(m2Tuple)
AssertTupleTypeEquality(m6Tuple)
Assert.False(m1Tuple.Equals(m2Tuple))
Assert.False(m1Tuple.Equals(m6Tuple))
Assert.False(m6Tuple.Equals(m2Tuple))
AssertTupleTypeMembersEquality(m1Tuple, m2Tuple)
AssertTupleTypeMembersEquality(m1Tuple, m6Tuple)
AssertTupleTypeMembersEquality(m2Tuple, m6Tuple)
Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(1), FieldSymbol)
AssertNonvirtualTupleElementField(m1Item1)
Assert.True(m1Item1.IsTupleField)
Assert.Same(m1Item1, m1Item1.OriginalDefinition)
Assert.True(m1Item1.Equals(m1Item1))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m1Item1.AssociatedSymbol)
Assert.Same(m1Tuple, m1Item1.ContainingSymbol)
Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol)
Assert.True(m1Item1.CustomModifiers.IsEmpty)
Assert.True(m1Item1.GetAttributes().IsEmpty)
Assert.Null(m1Item1.GetUseSiteErrorInfo())
Assert.False(m1Item1.Locations.IsEmpty)
Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty)
Assert.Equal("Item1", m1Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.True(m1Item1.IsImplicitlyDeclared)
Assert.Null(m1Item1.TypeLayoutOffset)
Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol)
AssertNonvirtualTupleElementField(m2Item1)
Assert.True(m2Item1.IsTupleField)
Assert.Same(m2Item1, m2Item1.OriginalDefinition)
Assert.True(m2Item1.Equals(m2Item1))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m2Item1.AssociatedSymbol)
Assert.Same(m2Tuple, m2Item1.ContainingSymbol)
Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol)
Assert.True(m2Item1.CustomModifiers.IsEmpty)
Assert.True(m2Item1.GetAttributes().IsEmpty)
Assert.Null(m2Item1.GetUseSiteErrorInfo())
Assert.False(m2Item1.Locations.IsEmpty)
Assert.True(m2Item1.DeclaringSyntaxReferences.IsEmpty)
Assert.Equal("Item1", m2Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single())
Assert.Equal("SourceFile(a.vb[760..765))", m2Item1.TupleUnderlyingField.Locations.Single().ToString())
Assert.Equal("SourceFile(a.vb[175..177))", m2Item1.Locations.Single().ToString())
Assert.True(m2Item1.IsImplicitlyDeclared)
Assert.Null(m2Item1.TypeLayoutOffset)
Dim m2a2 = DirectCast(m2Tuple.GetMembers()(2), FieldSymbol)
AssertVirtualTupleElementField(m2a2)
Assert.True(m2a2.IsTupleField)
Assert.Same(m2a2, m2a2.OriginalDefinition)
Assert.True(m2a2.Equals(m2a2))
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString())
Assert.Null(m2a2.AssociatedSymbol)
Assert.Same(m2Tuple, m2a2.ContainingSymbol)
Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol)
Assert.True(m2a2.CustomModifiers.IsEmpty)
Assert.True(m2a2.GetAttributes().IsEmpty)
Assert.Null(m2a2.GetUseSiteErrorInfo())
Assert.False(m2a2.Locations.IsEmpty)
Assert.Equal("a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.Equal("Item1", m2a2.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString())
Assert.False(m2a2.IsImplicitlyDeclared)
Assert.Null(m2a2.TypeLayoutOffset)
Dim m1ToString = m1Tuple.GetMember(Of MethodSymbol)("ToString")
Assert.True(m1ToString.IsTupleMethod)
Assert.Same(m1ToString, m1ToString.OriginalDefinition)
Assert.Same(m1ToString, m1ToString.ConstructedFrom)
Assert.Equal("Function System.ValueTuple(Of System.Int32, System.Int32).ToString() As System.String",
m1ToString.TupleUnderlyingMethod.ToTestDisplayString())
Assert.Same(m1ToString.TupleUnderlyingMethod, m1ToString.TupleUnderlyingMethod.ConstructedFrom)
Assert.Same(m1Tuple, m1ToString.ContainingSymbol)
Assert.Same(m1Tuple.TupleUnderlyingType, m1ToString.TupleUnderlyingMethod.ContainingType)
Assert.Null(m1ToString.AssociatedSymbol)
Assert.True(m1ToString.ExplicitInterfaceImplementations.IsEmpty)
Assert.False(m1ToString.ReturnType.SpecialType = SpecialType.System_Void)
Assert.True(m1ToString.TypeArguments.IsEmpty)
Assert.True(m1ToString.TypeParameters.IsEmpty)
Assert.True(m1ToString.GetAttributes().IsEmpty)
Assert.Null(m1ToString.GetUseSiteErrorInfo())
Assert.Equal("Function System.ValueType.ToString() As System.String",
m1ToString.OverriddenMethod.ToTestDisplayString())
Assert.False(m1ToString.Locations.IsEmpty)
Assert.Equal("Public Overrides Function ToString()", m1ToString.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 36))
Assert.Equal(m1ToString.Locations.Single(), m1ToString.TupleUnderlyingMethod.Locations.Single())
End Sub
<Fact>
Public Sub OverriddenMethodWithDifferentTupleNamesInReturn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Function M1() As (a As Integer, b As Integer)
Return (1, 2)
End Function
Public Overridable Function M2() As (a As Integer, b As Integer)
Return (1, 2)
End Function
Public Overridable Function M3() As (a As Integer, b As Integer)()
Return {(1, 2)}
End Function
Public Overridable Function M4() As (a As Integer, b As Integer)?
Return (1, 2)
End Function
Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer)
Return ((1, 2), 3)
End Function
End Class
Public Class Derived
Inherits Base
Public Overrides Function M1() As (A As Integer, B As Integer)
Return (1, 2)
End Function
Public Overrides Function M2() As (notA As Integer, notB As Integer)
Return (1, 2)
End Function
Public Overrides Function M3() As (notA As Integer, notB As Integer)()
Return {(1, 2)}
End Function
Public Overrides Function M4() As (notA As Integer, notB As Integer)?
Return (1, 2)
End Function
Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)
Return ((1, 2), 3)
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Function M2() As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Function M2() As (a As Integer, b As Integer)' because they differ by their tuple element names.
Public Overrides Function M2() As (notA As Integer, notB As Integer)
~~
BC40001: 'Public Overrides Function M3() As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Function M3() As (a As Integer, b As Integer)()' because they differ by their tuple element names.
Public Overrides Function M3() As (notA As Integer, notB As Integer)()
~~
BC40001: 'Public Overrides Function M4() As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Function M4() As (a As Integer, b As Integer)?' because they differ by their tuple element names.
Public Overrides Function M4() As (notA As Integer, notB As Integer)?
~~
BC40001: 'Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names.
Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)
~~
</errors>)
Dim m3 = comp.GetMember(Of MethodSymbol)("Derived.M3").ReturnType
Assert.Equal("(notA As System.Int32, notB As System.Int32)()", m3.ToTestDisplayString())
Assert.Equal({"System.Collections.Generic.IList(Of (notA As System.Int32, notB As System.Int32))"},
m3.Interfaces.SelectAsArray(Function(t) t.ToTestDisplayString()))
End Sub
<Fact>
Public Sub OverriddenMethodWithNoTupleNamesInReturn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Function M6() As (a As Integer, b As Integer)
Return (1, 2)
End Function
End Class
Public Class Derived
Inherits Base
Public Overrides Function M6() As (Integer, Integer)
Return (1, 2)
End Function
Sub M()
Dim result = Me.M6()
Dim result2 = MyBase.M6()
System.Console.Write(result.a)
System.Console.Write(result2.a)
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30456: 'a' is not a member of '(Integer, Integer)'.
System.Console.Write(result.a)
~~~~~~~~
</errors>)
Dim m6 = comp.GetMember(Of MethodSymbol)("Derived.M6").ReturnType
Assert.Equal("(System.Int32, System.Int32)", m6.ToTestDisplayString())
Dim tree = comp.SyntaxTrees.First()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim invocation = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(0)
Assert.Equal("Me.M6()", invocation.ToString())
Assert.Equal("Function Derived.M6() As (System.Int32, System.Int32)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString())
Dim invocation2 = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(1)
Assert.Equal("MyBase.M6()", invocation2.ToString())
Assert.Equal("Function Base.M6() As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(invocation2).Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub OverriddenMethodWithDifferentTupleNamesInReturnUsingTypeArg()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Function M1(Of T)() As (a As T, b As T)
Return (Nothing, Nothing)
End Function
Public Overridable Function M2(Of T)() As (a As T, b As T)
Return (Nothing, Nothing)
End Function
Public Overridable Function M3(Of T)() As (a As T, b As T)()
Return {(Nothing, Nothing)}
End Function
Public Overridable Function M4(Of T)() As (a As T, b As T)?
Return (Nothing, Nothing)
End Function
Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T)
Return ((Nothing, Nothing), Nothing)
End Function
End Class
Public Class Derived
Inherits Base
Public Overrides Function M1(Of T)() As (A As T, B As T)
Return (Nothing, Nothing)
End Function
Public Overrides Function M2(Of T)() As (notA As T, notB As T)
Return (Nothing, Nothing)
End Function
Public Overrides Function M3(Of T)() As (notA As T, notB As T)()
Return {(Nothing, Nothing)}
End Function
Public Overrides Function M4(Of T)() As (notA As T, notB As T)?
Return (Nothing, Nothing)
End Function
Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T)
Return ((Nothing, Nothing), Nothing)
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Function M2(Of T)() As (notA As T, notB As T)' cannot override 'Public Overridable Function M2(Of T)() As (a As T, b As T)' because they differ by their tuple element names.
Public Overrides Function M2(Of T)() As (notA As T, notB As T)
~~
BC40001: 'Public Overrides Function M3(Of T)() As (notA As T, notB As T)()' cannot override 'Public Overridable Function M3(Of T)() As (a As T, b As T)()' because they differ by their tuple element names.
Public Overrides Function M3(Of T)() As (notA As T, notB As T)()
~~
BC40001: 'Public Overrides Function M4(Of T)() As (notA As T, notB As T)?' cannot override 'Public Overridable Function M4(Of T)() As (a As T, b As T)?' because they differ by their tuple element names.
Public Overrides Function M4(Of T)() As (notA As T, notB As T)?
~~
BC40001: 'Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T)' cannot override 'Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T)' because they differ by their tuple element names.
Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T)
~~
</errors>)
End Sub
<Fact>
Public Sub OverriddenMethodWithDifferentTupleNamesInParameters()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Sub M1(x As (a As Integer, b As Integer))
End Sub
Public Overridable Sub M2(x As (a As Integer, b As Integer))
End Sub
Public Overridable Sub M3(x As (a As Integer, b As Integer)())
End Sub
Public Overridable Sub M4(x As (a As Integer, b As Integer)?)
End Sub
Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))
End Sub
End Class
Public Class Derived
Inherits Base
Public Overrides Sub M1(x As (A As Integer, B As Integer))
End Sub
Public Overrides Sub M2(x As (notA As Integer, notB As Integer))
End Sub
Public Overrides Sub M3(x As (notA As Integer, notB As Integer)())
End Sub
Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?)
End Sub
Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Sub M2(x As (notA As Integer, notB As Integer))' cannot override 'Public Overridable Sub M2(x As (a As Integer, b As Integer))' because they differ by their tuple element names.
Public Overrides Sub M2(x As (notA As Integer, notB As Integer))
~~
BC40001: 'Public Overrides Sub M3(x As (notA As Integer, notB As Integer)())' cannot override 'Public Overridable Sub M3(x As (a As Integer, b As Integer)())' because they differ by their tuple element names.
Public Overrides Sub M3(x As (notA As Integer, notB As Integer)())
~~
BC40001: 'Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?)' cannot override 'Public Overridable Sub M4(x As (a As Integer, b As Integer)?)' because they differ by their tuple element names.
Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?)
~~
BC40001: 'Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' cannot override 'Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))' because they differ by their tuple element names.
Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
~~
</errors>)
End Sub
<Fact>
Public Sub OverriddenMethodWithDifferentTupleNamesInParametersUsingTypeArg()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Sub M1(Of T)(x As (a As T, b As T))
End Sub
Public Overridable Sub M2(Of T)(x As (a As T, b As T))
End Sub
Public Overridable Sub M3(Of T)(x As (a As T, b As T)())
End Sub
Public Overridable Sub M4(Of T)(x As (a As T, b As T)?)
End Sub
Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T))
End Sub
End Class
Public Class Derived
Inherits Base
Public Overrides Sub M1(Of T)(x As (A As T, B As T))
End Sub
Public Overrides Sub M2(Of T)(x As (notA As T, notB As T))
End Sub
Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)())
End Sub
Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?)
End Sub
Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Sub M2(Of T)(x As (notA As T, notB As T))' cannot override 'Public Overridable Sub M2(Of T)(x As (a As T, b As T))' because they differ by their tuple element names.
Public Overrides Sub M2(Of T)(x As (notA As T, notB As T))
~~
BC40001: 'Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)())' cannot override 'Public Overridable Sub M3(Of T)(x As (a As T, b As T)())' because they differ by their tuple element names.
Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)())
~~
BC40001: 'Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?)' cannot override 'Public Overridable Sub M4(Of T)(x As (a As T, b As T)?)' because they differ by their tuple element names.
Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?)
~~
BC40001: 'Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T))' cannot override 'Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T))' because they differ by their tuple element names.
Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T))
~~
</errors>)
End Sub
<Fact>
Public Sub HiddenMethodsWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Function M1() As (a As Integer, b As Integer)
Return (1, 2)
End Function
Public Overridable Function M2() As (a As Integer, b As Integer)
Return (1, 2)
End Function
Public Overridable Function M3() As (a As Integer, b As Integer)()
Return {(1, 2)}
End Function
Public Overridable Function M4() As (a As Integer, b As Integer)?
Return (1, 2)
End Function
Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer)
Return ((1, 2), 3)
End Function
End Class
Public Class Derived
Inherits Base
Public Function M1() As (A As Integer, B As Integer)
Return (1, 2)
End Function
Public Function M2() As (notA As Integer, notB As Integer)
Return (1, 2)
End Function
Public Function M3() As (notA As Integer, notB As Integer)()
Return {(1, 2)}
End Function
Public Function M4() As (notA As Integer, notB As Integer)?
Return (1, 2)
End Function
Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)
Return ((1, 2), 3)
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40005: function 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Function M1() As (A As Integer, B As Integer)
~~
BC40005: function 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Function M2() As (notA As Integer, notB As Integer)
~~
BC40005: function 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Function M3() As (notA As Integer, notB As Integer)()
~~
BC40005: function 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Function M4() As (notA As Integer, notB As Integer)?
~~
BC40005: function 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)
~~
</errors>)
End Sub
<Fact>
Public Sub DuplicateMethodDetectionWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Sub M1(x As (A As Integer, B As Integer))
End Sub
Public Sub M1(x As (a As Integer, b As Integer))
End Sub
Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer))
End Sub
Public Sub M2(x As (a As Integer, b As Integer))
End Sub
Public Sub M3(x As (notA As Integer, notB As Integer)())
End Sub
Public Sub M3(x As (a As Integer, b As Integer)())
End Sub
Public Sub M4(x As (notA As Integer, notB As Integer)?)
End Sub
Public Sub M4(x As (a As Integer, b As Integer)?)
End Sub
Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
End Sub
Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30269: 'Public Sub M1(x As (A As Integer, B As Integer))' has multiple definitions with identical signatures.
Public Sub M1(x As (A As Integer, B As Integer))
~~
BC37271: 'Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M2(x As (a As Integer, b As Integer))'.
Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer))
~~
BC37271: 'Public Sub M3(x As (notA As Integer, notB As Integer)())' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M3(x As (a As Integer, b As Integer)())'.
Public Sub M3(x As (notA As Integer, notB As Integer)())
~~
BC37271: 'Public Sub M4(x As (notA As Integer, notB As Integer)?)' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M4(x As (a As Integer, b As Integer)?)'.
Public Sub M4(x As (notA As Integer, notB As Integer)?)
~~
BC37271: 'Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))'.
Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
~~
</errors>)
End Sub
<Fact>
Public Sub HiddenMethodParametersWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Sub M1(x As (a As Integer, b As Integer))
End Sub
Public Overridable Sub M2(x As (a As Integer, b As Integer))
End Sub
Public Overridable Sub M3(x As (a As Integer, b As Integer)())
End Sub
Public Overridable Sub M4(x As (a As Integer, b As Integer)?)
End Sub
Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))
End Sub
End Class
Public Class Derived
Inherits Base
Public Sub M1(x As (A As Integer, B As Integer))
End Sub
Public Sub M2(x As (notA As Integer, notB As Integer))
End Sub
Public Sub M3(x As (notA As Integer, notB As Integer)())
End Sub
Public Sub M4(x As (notA As Integer, notB As Integer)?)
End Sub
Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40005: sub 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Sub M1(x As (A As Integer, B As Integer))
~~
BC40005: sub 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Sub M2(x As (notA As Integer, notB As Integer))
~~
BC40005: sub 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Sub M3(x As (notA As Integer, notB As Integer)())
~~
BC40005: sub 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Sub M4(x As (notA As Integer, notB As Integer)?)
~~
BC40005: sub 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'.
Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))
~~
</errors>)
End Sub
<Fact>
Public Sub ExplicitInterfaceImplementationWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0
Sub M1(x As (Integer, (Integer, c As Integer)))
Sub M2(x As (a As Integer, (b As Integer, c As Integer)))
Function MR1() As (Integer, (Integer, c As Integer))
Function MR2() As (a As Integer, (b As Integer, c As Integer))
End Interface
Public Class Derived
Implements I0
Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1
End Sub
Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2
End Sub
Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1
Return (1, (2, 3))
End Function
Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2
Return (1, (2, 3))
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30402: 'M1' cannot implement sub 'M1' on interface 'I0' because the tuple element names in 'Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer)))' do not match those in 'Sub M1(x As (Integer, (Integer, c As Integer)))'.
Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1
~~~~~
BC30402: 'M2' cannot implement sub 'M2' on interface 'I0' because the tuple element names in 'Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer)))' do not match those in 'Sub M2(x As (a As Integer, (b As Integer, c As Integer)))'.
Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2
~~~~~
BC30402: 'MR1' cannot implement function 'MR1' on interface 'I0' because the tuple element names in 'Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer))' do not match those in 'Function MR1() As (Integer, (Integer, c As Integer))'.
Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1
~~~~~~
BC30402: 'MR2' cannot implement function 'MR2' on interface 'I0' because the tuple element names in 'Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer))' do not match those in 'Function MR2() As (a As Integer, (b As Integer, c As Integer))'.
Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2
~~~~~~
</errors>)
End Sub
<Fact>
Public Sub InterfaceImplementationOfPropertyWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0
Property P1 As (a As Integer, b As Integer)
Property P2 As (Integer, b As Integer)
End Interface
Public Class Derived
Implements I0
Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1
Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30402: 'P1' cannot implement property 'P1' on interface 'I0' because the tuple element names in 'Public Property P1 As (notA As Integer, notB As Integer)' do not match those in 'Property P1 As (a As Integer, b As Integer)'.
Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1
~~~~~
BC30402: 'P2' cannot implement property 'P2' on interface 'I0' because the tuple element names in 'Public Property P2 As (notMissing As Integer, b As Integer)' do not match those in 'Property P2 As (Integer, b As Integer)'.
Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2
~~~~~
</errors>)
End Sub
<Fact>
Public Sub InterfaceImplementationOfEventWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Interface I0
Event E1 As Action(Of (a As Integer, b As Integer))
Event E2 As Action(Of (Integer, b As Integer))
End Interface
Public Class Derived
Implements I0
Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1
Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30402: 'E1' cannot implement event 'E1' on interface 'I0' because the tuple element names in 'Public Event E1 As Action(Of (notA As Integer, notB As Integer))' do not match those in 'Event E1 As Action(Of (a As Integer, b As Integer))'.
Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1
~~~~~
BC30402: 'E2' cannot implement event 'E2' on interface 'I0' because the tuple element names in 'Public Event E2 As Action(Of (notMissing As Integer, notB As Integer))' do not match those in 'Event E2 As Action(Of (Integer, b As Integer))'.
Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2
~~~~~
</errors>)
End Sub
<Fact>
Public Sub InterfaceHidingAnotherInterfaceWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0
Sub M1(x As (a As Integer, b As Integer))
Sub M2(x As (a As Integer, b As Integer))
Function MR1() As (a As Integer, b As Integer)
Function MR2() As (a As Integer, b As Integer)
End Interface
Public Interface I1
Inherits I0
Sub M1(x As (notA As Integer, b As Integer))
Shadows Sub M2(x As (notA As Integer, b As Integer))
Function MR1() As (notA As Integer, b As Integer)
Shadows Function MR2() As (notA As Integer, b As Integer)
End Interface
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40003: sub 'M1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'.
Sub M1(x As (notA As Integer, b As Integer))
~~
BC40003: function 'MR1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'.
Function MR1() As (notA As Integer, b As Integer)
~~~
</errors>)
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0(Of T)
End Interface
Public Class C1
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
End Class
Public Class C2
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer))
End Class
Public Class C3
Implements I0(Of Integer), I0(Of Integer)
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type.
Implements I0(Of Integer), I0(Of Integer)
~~~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees.First()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim c1 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(1))
Assert.Equal("C1", c1.Name)
Assert.Equal(2, c1.AllInterfaces.Count)
Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c1.AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I0(Of (notA As System.Int32, notB As System.Int32))", c1.AllInterfaces(1).ToTestDisplayString())
Dim c2 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(2))
Assert.Equal("C2", c2.Name)
Assert.Equal(1, c2.AllInterfaces.Count)
Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c2.AllInterfaces(0).ToTestDisplayString())
Dim c3 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(3))
Assert.Equal("C3", c3.Name)
Assert.Equal(1, c3.AllInterfaces.Count)
Assert.Equal("I0(Of System.Int32)", c3.AllInterfaces(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public interface I1(Of T)
Sub M()
end interface
public interface I2
Inherits I1(Of (a As Integer, b As Integer))
end interface
public interface I3
Inherits I1(Of (c As Integer, d As Integer))
end interface
public class C1
Implements I2, I1(Of (c As Integer, d As Integer))
Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M
End Sub
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1
End Sub
End class
public class C2
Implements I1(Of (c As Integer, d As Integer)), I2
Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M
End Sub
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2
End Sub
End class
public class C3
Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer))
Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M
End Sub
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3
End Sub
End class
public class C4
Implements I2, I3
Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M
End Sub
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4
End Sub
End class
</file>
</compilation>
)
comp.AssertTheseDiagnostics(
<errors>
BC37273: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2').
Implements I2, I1(Of (c As Integer, d As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37274: Interface 'I1(Of (a As Integer, b As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As Integer, d As Integer))'.
Implements I1(Of (c As Integer, d As Integer)), I2
~~
BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37272: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))'.
Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37275: Interface 'I1(Of (c As Integer, d As Integer))' (via 'I3') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2').
Implements I2, I3
~~
BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1")
Dim c1Interfaces = c1.Interfaces
Dim c1AllInterfaces = c1.AllInterfaces
Assert.Equal(2, c1Interfaces.Length)
Assert.Equal(3, c1AllInterfaces.Length)
Assert.Equal("I2", c1Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1Interfaces(1).ToTestDisplayString())
Assert.Equal("I2", c1AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1AllInterfaces(2).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c1)
Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2")
Dim c2Interfaces = c2.Interfaces
Dim c2AllInterfaces = c2.AllInterfaces
Assert.Equal(2, c2Interfaces.Length)
Assert.Equal(3, c2AllInterfaces.Length)
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString())
Assert.Equal("I2", c2Interfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I2", c2AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(2).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c2)
Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3")
Dim c3Interfaces = c3.Interfaces
Dim c3AllInterfaces = c3.AllInterfaces
Assert.Equal(2, c3Interfaces.Length)
Assert.Equal(2, c3AllInterfaces.Length)
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3Interfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3AllInterfaces(1).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c3)
Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4")
Dim c4Interfaces = c4.Interfaces
Dim c4AllInterfaces = c4.AllInterfaces
Assert.Equal(2, c4Interfaces.Length)
Assert.Equal(4, c4AllInterfaces.Length)
Assert.Equal("I2", c4Interfaces(0).ToTestDisplayString())
Assert.Equal("I3", c4Interfaces(1).ToTestDisplayString())
Assert.Equal("I2", c4AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c4AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I3", c4AllInterfaces(2).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c4AllInterfaces(3).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c4)
End Sub
Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol)
Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMabImplementations.Length)
Assert.Equal("Sub I1(Of (a As System.Int32, b As System.Int32)).M()", cMabImplementations(0).ToTestDisplayString())
Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMcdImplementations.Length)
Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", cMcdImplementations(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_03()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public interface I1(Of T)
Sub M()
end interface
public class C1
Implements I1(Of (a As Integer, b As Integer))
Sub M() Implements I1(Of (a As Integer, b As Integer)).M
System.Console.WriteLine("C1.M")
End Sub
End class
public class C2
Inherits C1
Implements I1(Of (c As Integer, d As Integer))
Overloads Sub M() Implements I1(Of (c As Integer, d As Integer)).M
System.Console.WriteLine("C2.M")
End Sub
Shared Sub Main()
Dim x As C1 = new C2()
Dim y As I1(Of (a As Integer, b As Integer)) = x
y.M()
End Sub
End class
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics()
Dim validate As Action(Of ModuleSymbol) =
Sub(m)
Dim isMetadata As Boolean = TypeOf m Is PEModuleSymbol
Dim c1 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C1")
Dim c1Interfaces = c1.Interfaces
Dim c1AllInterfaces = c1.AllInterfaces
Assert.Equal(1, c1Interfaces.Length)
Assert.Equal(1, c1AllInterfaces.Length)
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString())
Dim c2 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C2")
Dim c2Interfaces = c2.Interfaces
Dim c2AllInterfaces = c2.AllInterfaces
Assert.Equal(1, c2Interfaces.Length)
Assert.Equal(2, c2AllInterfaces.Length)
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString())
Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol)
Dim m2Implementations = m2.ExplicitInterfaceImplementations
Assert.Equal(1, m2Implementations.Length)
Assert.Equal(If(isMetadata,
"Sub I1(Of (System.Int32, System.Int32)).M()",
"Sub I1(Of (c As System.Int32, d As System.Int32)).M()"),
m2Implementations(0).ToTestDisplayString())
Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M")))
End Sub
CompileAndVerify(comp, sourceSymbolValidator:=validate, symbolValidator:=validate, expectedOutput:="C2.M")
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_04()
Dim csSource = "
public interface I1<T>
{
void M();
}
public class C1 : I1<(int a, int b)>
{
public void M() => System.Console.WriteLine(""C1.M"");
}
public class C2 : C1, I1<(int c, int d)>
{
new public void M() => System.Console.WriteLine(""C2.M"");
}
"
Dim csComp = CreateCSharpCompilation(csSource,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime))
csComp.VerifyDiagnostics()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public class C3
Shared Sub Main()
Dim x As C1 = new C2()
Dim y As I1(Of (a As Integer, b As Integer)) = x
y.M()
End Sub
End class
</file>
</compilation>,
options:=TestOptions.DebugExe, references:={csComp.EmitToImageReference()})
comp.AssertTheseDiagnostics()
CompileAndVerify(comp, expectedOutput:="C2.M")
Dim c1 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1")
Dim c1Interfaces = c1.Interfaces
Dim c1AllInterfaces = c1.AllInterfaces
Assert.Equal(1, c1Interfaces.Length)
Assert.Equal(1, c1AllInterfaces.Length)
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString())
Dim c2 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C2")
Dim c2Interfaces = c2.Interfaces
Dim c2AllInterfaces = c2.AllInterfaces
Assert.Equal(1, c2Interfaces.Length)
Assert.Equal(2, c2AllInterfaces.Length)
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString())
Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol)
Dim m2Implementations = m2.ExplicitInterfaceImplementations
Assert.Equal(0, m2Implementations.Length)
Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M")))
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public interface I1(Of T)
Sub M()
end interface
public interface I2(Of I2T)
Inherits I1(Of (a As I2T, b As I2T))
end interface
public interface I3(Of I3T)
Inherits I1(Of (c As I3T, d As I3T))
end interface
public class C1(Of T)
Implements I2(Of T), I1(Of (c As T, d As T))
Sub M_1() Implements I1(Of (a As T, b As T)).M
End Sub
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1
End Sub
End class
public class C2(Of T)
Implements I1(Of (c As T, d As T)), I2(Of T)
Sub M_1() Implements I1(Of (a As T, b As T)).M
End Sub
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2
End Sub
End class
public class C3(Of T)
Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T))
Sub M_1() Implements I1(Of (a As T, b As T)).M
End Sub
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3
End Sub
End class
public class C4(Of T)
Implements I2(Of T), I3(Of T)
Sub M_1() Implements I1(Of (a As T, b As T)).M
End Sub
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4
End Sub
End class
</file>
</compilation>
)
comp.AssertTheseDiagnostics(
<errors>
BC37273: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)').
Implements I2(Of T), I1(Of (c As T, d As T))
~~~~~~~~~~~~~~~~~~~~~~~
BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1
~~~~~~~~~~~~~~~~~~~~~~~~~
BC37274: Interface 'I1(Of (a As T, b As T))' (via 'I2(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As T, d As T))'.
Implements I1(Of (c As T, d As T)), I2(Of T)
~~~~~~~~
BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2
~~~~~~~~~~~~~~~~~~~~~~~~~
BC37272: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))'.
Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T))
~~~~~~~~~~~~~~~~~~~~~~~
BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3
~~~~~~~~~~~~~~~~~~~~~~~~~
BC37275: Interface 'I1(Of (c As T, d As T))' (via 'I3(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)').
Implements I2(Of T), I3(Of T)
~~~~~~~~
BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once.
Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4
~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1`1")
Dim c1Interfaces = c1.Interfaces
Dim c1AllInterfaces = c1.AllInterfaces
Assert.Equal(2, c1Interfaces.Length)
Assert.Equal(3, c1AllInterfaces.Length)
Assert.Equal("I2(Of T)", c1Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c1Interfaces(1).ToTestDisplayString())
Assert.Equal("I2(Of T)", c1AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As T, b As T))", c1AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c1AllInterfaces(2).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c1)
Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2`1")
Dim c2Interfaces = c2.Interfaces
Dim c2AllInterfaces = c2.AllInterfaces
Assert.Equal(2, c2Interfaces.Length)
Assert.Equal(3, c2AllInterfaces.Length)
Assert.Equal("I1(Of (c As T, d As T))", c2Interfaces(0).ToTestDisplayString())
Assert.Equal("I2(Of T)", c2Interfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c2AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I2(Of T)", c2AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (a As T, b As T))", c2AllInterfaces(2).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c2)
Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`1")
Dim c3Interfaces = c3.Interfaces
Dim c3AllInterfaces = c3.AllInterfaces
Assert.Equal(2, c3Interfaces.Length)
Assert.Equal(2, c3AllInterfaces.Length)
Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c3Interfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c3AllInterfaces(1).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c3)
Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4`1")
Dim c4Interfaces = c4.Interfaces
Dim c4AllInterfaces = c4.AllInterfaces
Assert.Equal(2, c4Interfaces.Length)
Assert.Equal(4, c4AllInterfaces.Length)
Assert.Equal("I2(Of T)", c4Interfaces(0).ToTestDisplayString())
Assert.Equal("I3(Of T)", c4Interfaces(1).ToTestDisplayString())
Assert.Equal("I2(Of T)", c4AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As T, b As T))", c4AllInterfaces(1).ToTestDisplayString())
Assert.Equal("I3(Of T)", c4AllInterfaces(2).ToTestDisplayString())
Assert.Equal("I1(Of (c As T, d As T))", c4AllInterfaces(3).ToTestDisplayString())
DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c4)
End Sub
Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol)
Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMabImplementations.Length)
Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString())
Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMcdImplementations.Length)
Assert.Equal("Sub I1(Of (c As T, d As T)).M()", cMcdImplementations(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_06()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public interface I1(Of T)
Sub M()
end interface
public class C3(Of T, U)
Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U))
Sub M_1() Implements I1(Of (a As T, b As T)).M
End Sub
Sub M_2() Implements I1(Of (c As U, d As U)).M
End Sub
End class
</file>
</compilation>
)
comp.AssertTheseDiagnostics(
<errors>
BC32072: Cannot implement interface 'I1(Of (c As U, d As U))' because its implementation could conflict with the implementation of another implemented interface 'I1(Of (a As T, b As T))' for some type arguments.
Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U))
~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`2")
Dim c3Interfaces = c3.Interfaces
Dim c3AllInterfaces = c3.AllInterfaces
Assert.Equal(2, c3Interfaces.Length)
Assert.Equal(2, c3AllInterfaces.Length)
Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As U, d As U))", c3Interfaces(1).ToTestDisplayString())
Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (c As U, d As U))", c3AllInterfaces(1).ToTestDisplayString())
Dim cMabImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMabImplementations.Length)
Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString())
Dim cMcdImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, cMcdImplementations.Length)
Assert.Equal("Sub I1(Of (c As U, d As U)).M()", cMcdImplementations(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_07()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb">
public interface I1(Of T)
Sub M()
end interface
public class C3
Implements I1(Of (a As Integer, b As Integer))
Sub M() Implements I1(Of (c As Integer, d As Integer)).M
End Sub
End class
public class C4
Implements I1(Of (c As Integer, d As Integer))
Sub M() Implements I1(Of (c As Integer, d As Integer)).M
End Sub
End class
</file>
</compilation>
)
comp.AssertTheseDiagnostics(
<errors>
BC31035: Interface 'I1(Of (c As Integer, d As Integer))' is not implemented by this class.
Sub M() Implements I1(Of (c As Integer, d As Integer)).M
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3")
Dim c3Interfaces = c3.Interfaces
Dim c3AllInterfaces = c3.AllInterfaces
Assert.Equal(1, c3Interfaces.Length)
Assert.Equal(1, c3AllInterfaces.Length)
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString())
Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString())
Dim mImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M"), IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, mImplementations.Length)
Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", mImplementations(0).ToTestDisplayString())
Assert.Equal("Sub C3.M()",
c3.FindImplementationForInterfaceMember(DirectCast(c3Interfaces(0), TypeSymbol).GetMember("M")).ToTestDisplayString())
Assert.Equal("Sub C3.M()",
c3.FindImplementationForInterfaceMember(comp.GetTypeByMetadataName("C4").InterfacesNoUseSiteDiagnostics()(0).GetMember("M")).ToTestDisplayString())
End Sub
<Fact>
Public Sub AccessCheckLooksInsideTuples()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Function M() As (C2.C3, Integer)
Throw New System.Exception()
End Function
End Class
Public Class C2
Private Class C3
End Class
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30389: 'C2.C3' is not accessible in this context because it is 'Private'.
Public Function M() As (C2.C3, Integer)
~~~~~
</errors>)
End Sub
<Fact>
Public Sub AccessCheckLooksInsideTuples2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Function M() As (C2, Integer)
Throw New System.Exception()
End Function
Private Class C2
End Class
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
Dim expectedErrors = <errors><![CDATA[
BC30508: 'M' cannot expose type 'C.C2' in namespace '<Default>' through class 'C'.
Public Function M() As (C2, Integer)
~~~~~~~~~~~~~
]]></errors>
comp.AssertTheseDiagnostics(expectedErrors)
End Sub
<Fact>
Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0(Of T)
End Interface
Public Class C2
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer))
End Class
Public Class C3
Implements I0(Of Integer), I0(Of Integer)
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type.
Implements I0(Of Integer), I0(Of Integer)
~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub ImplicitAndExplicitInterfaceImplementationWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Interface I0(Of T)
Function Pop() As T
Sub Push(x As T)
End Interface
Public Class C1
Implements I0(Of (a As Integer, b As Integer))
Public Function Pop() As (a As Integer, b As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop
Throw New Exception()
End Function
Public Sub Push(x As (a As Integer, b As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push
End Sub
End Class
Public Class C2
Inherits C1
Implements I0(Of (a As Integer, b As Integer))
Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop
Throw New Exception()
End Function
Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30402: 'Pop' cannot implement function 'Pop' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Function Pop() As (notA As Integer, notB As Integer)' do not match those in 'Function Pop() As (a As Integer, b As Integer)'.
Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30402: 'Push' cannot implement sub 'Push' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Sub Push(x As (notA As Integer, notB As Integer))' do not match those in 'Sub Push(x As (a As Integer, b As Integer))'.
Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub PartialMethodsWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Partial Class C1
Private Partial Sub M1(x As (a As Integer, b As Integer))
End Sub
Private Partial Sub M2(x As (a As Integer, b As Integer))
End Sub
Private Partial Sub M3(x As (a As Integer, b As Integer))
End Sub
End Class
Public Partial Class C1
Private Sub M1(x As (notA As Integer, notB As Integer))
End Sub
Private Sub M2(x As (Integer, Integer))
End Sub
Private Sub M3(x As (a As Integer, b As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37271: 'Private Sub M1(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M1(x As (notA As Integer, notB As Integer))'.
Private Partial Sub M1(x As (a As Integer, b As Integer))
~~
BC37271: 'Private Sub M2(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M2(x As (Integer, Integer))'.
Private Partial Sub M2(x As (a As Integer, b As Integer))
~~
</errors>)
End Sub
<Fact>
Public Sub PartialClassWithDifferentTupleNamesInBaseInterfaces()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0(Of T)
End Interface
Public Partial Class C
Implements I0(Of (a As Integer, b As Integer))
End Class
Public Partial Class C
Implements I0(Of (notA As Integer, notB As Integer))
End Class
Public Partial Class C
Implements I0(Of (Integer, Integer))
End Class
Public Partial Class D
Implements I0(Of (a As Integer, b As Integer))
End Class
Public Partial Class D
Implements I0(Of (a As Integer, b As Integer))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Implements I0(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37272: Interface 'I0(Of (Integer, Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Implements I0(Of (Integer, Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub PartialClassWithDifferentTupleNamesInBaseTypes()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base(Of T)
End Class
Public Partial Class C1
Inherits Base(Of (a As Integer, b As Integer))
End Class
Public Partial Class C1
Inherits Base(Of (notA As Integer, notB As Integer))
End Class
Public Partial Class C2
Inherits Base(Of (a As Integer, b As Integer))
End Class
Public Partial Class C2
Inherits Base(Of (Integer, Integer))
End Class
Public Partial Class C3
Inherits Base(Of (a As Integer, b As Integer))
End Class
Public Partial Class C3
Inherits Base(Of (a As Integer, b As Integer))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30928: Base class 'Base(Of (notA As Integer, notB As Integer))' specified for class 'C1' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types.
Inherits Base(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30928: Base class 'Base(Of (Integer, Integer))' specified for class 'C2' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types.
Inherits Base(Of (Integer, Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub IndirectInterfaceBasesWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0(Of T)
End Interface
Public Interface I1
Inherits I0(Of (a As Integer, b As Integer))
End Interface
Public Interface I2
Inherits I0(Of (notA As Integer, notB As Integer))
End Interface
Public Interface I3
Inherits I0(Of (a As Integer, b As Integer))
End Interface
Public Class C1
Implements I1, I3
End Class
Public Class C2
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
End Class
Public Class C3
Implements I2, I0(Of (a As Integer, b As Integer))
End Class
Public Class C4
Implements I0(Of (a As Integer, b As Integer)), I2
End Class
Public Class C5
Implements I1, I2
End Class
Public Interface I11
Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
End Interface
Public Interface I12
Inherits I2, I0(Of (a As Integer, b As Integer))
End Interface
Public Interface I13
Inherits I0(Of (a As Integer, b As Integer)), I2
End Interface
Public Interface I14
Inherits I1, I2
End Interface
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37273: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2').
Implements I2, I0(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37274: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Implements I0(Of (a As Integer, b As Integer)), I2
~~
BC37275: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1').
Implements I1, I2
~~
BC37276: Interface 'I0(Of (notA As Integer, notB As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37277: Interface 'I0(Of (a As Integer, b As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2').
Inherits I2, I0(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37278: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'.
Inherits I0(Of (a As Integer, b As Integer)), I2
~~
BC37279: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1').
Inherits I1, I2
~~
</errors>)
End Sub
<Fact>
Public Sub InterfaceUnification()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0(Of T1)
End Interface
Public Class C1(Of T2)
Implements I0(Of Integer), I0(Of T2)
End Class
Public Class C2(Of T2)
Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2))
End Class
Public Class C3(Of T2)
Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2))
End Class
Public Class C4(Of T2)
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC32072: Cannot implement interface 'I0(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I0(Of Integer)' for some type arguments.
Implements I0(Of Integer), I0(Of T2)
~~~~~~~~~
BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (Integer, Integer))' for some type arguments.
Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2))
~~~~~~~~~~~~~~~
BC32072: Cannot implement interface 'I0(Of (a As T2, b As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2))
~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub InterfaceUnification2()
Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Public Interface I0(Of T1)
End Interface
Public Class Derived(Of T)
Implements I0(Of Derived(Of (T, T))), I0(Of T)
End Class
]]></file>
</compilation>,
references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
</errors>)
' Didn't run out of memory in trying to substitute T with Derived(Of (T, T)) in a loop
End Sub
<Fact>
Public Sub AmbiguousExtensionMethodWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Module M1
<System.Runtime.CompilerServices.Extension()>
Public Sub M(self As String, x As (Integer, Integer))
Throw New Exception()
End Sub
End Module
Public Module M2
<System.Runtime.CompilerServices.Extension()>
Public Sub M(self As String, x As (a As Integer, b As Integer))
Throw New Exception()
End Sub
End Module
Public Module M3
<System.Runtime.CompilerServices.Extension()>
Public Sub M(self As String, x As (c As Integer, d As Integer))
Throw New Exception()
End Sub
End Module
Public Class C
Public Sub M(s As String)
s.M((1, 1))
s.M((a:=1, b:=1))
s.M((c:=1, d:=1))
End Sub
End Class
]]></file>
</compilation>,
references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments:
Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific.
Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific.
Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific.
s.M((1, 1))
~
BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments:
Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific.
Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific.
Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific.
s.M((a:=1, b:=1))
~
BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments:
Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific.
Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific.
Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific.
s.M((c:=1, d:=1))
~
</errors>)
End Sub
<Fact>
Public Sub InheritFromMetadataWithDifferentNames()
Dim il =
"
.assembly extern mscorlib { }
.assembly extern System.ValueTuple
{
.publickeytoken = (CC 7B 13 FF CD 2D DD 51 )
.ver 4:0:1:0
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance class [System.ValueTuple]System.ValueTuple`2<int32,int32>
M() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
= {string[2]('a' 'b')}
// Code size 13 (0xd)
.maxstack 2
.locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0,
!1)
IL_0008: stloc.0
IL_0009: br.s IL_000b
IL_000b: ldloc.0
IL_000c: ret
} // end of method Base::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Base::.ctor
} // end of class Base
.class public auto ansi beforefieldinit Base2
extends Base
{
.method public hidebysig virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32>
M() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[])
= {string[2]('notA' 'notB')}
// Code size 13 (0xd)
.maxstack 2
.locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0,
!1)
IL_0008: stloc.0
IL_0009: br.s IL_000b
IL_000b: ldloc.0
IL_000c: ret
} // end of method Base2::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void Base::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Base2::.ctor
} // end of class Base2
"
Dim compMatching = CreateCompilationWithCustomILSource(
<compilation>
<file name="a.vb">
Public Class C
Inherits Base2
Public Overrides Function M() As (notA As Integer, notB As Integer)
Return (1, 2)
End Function
End Class
</file>
</compilation>,
il,
additionalReferences:=s_valueTupleRefs)
compMatching.AssertTheseDiagnostics()
Dim compDifferent1 = CreateCompilationWithCustomILSource(
<compilation>
<file name="a.vb">
Public Class C
Inherits Base2
Public Overrides Function M() As (a As Integer, b As Integer)
Return (1, 2)
End Function
End Class
</file>
</compilation>,
il,
additionalReferences:=s_valueTupleRefs)
compDifferent1.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Function M() As (a As Integer, b As Integer)' cannot override 'Public Overrides Function M() As (notA As Integer, notB As Integer)' because they differ by their tuple element names.
Public Overrides Function M() As (a As Integer, b As Integer)
~
</errors>)
Dim compDifferent2 = CreateCompilationWithCustomILSource(
<compilation>
<file name="a.vb">
Public Class C
Inherits Base2
Public Overrides Function M() As (Integer, Integer)
Return (1, 2)
End Function
End Class
</file>
</compilation>,
il,
additionalReferences:=s_valueTupleRefs)
compDifferent2.AssertTheseDiagnostics(
<errors>
</errors>)
End Sub
<Fact>
Public Sub TupleNamesInAnonymousTypes()
Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Public Shared Sub Main()
Dim x1 = New With {.Tuple = (a:=1, b:=2) }
Dim x2 = New With {.Tuple = (c:=1, 2) }
x2 = x1
Console.Write(x1.Tuple.a)
End Sub
End Class
</file>
</compilation>,
references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0))
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().First()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Assert.Equal("x1 As <anonymous type: Tuple As (a As System.Int32, b As System.Int32)>", model.GetDeclaredSymbol(x1).ToTestDisplayString())
Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0)
Assert.Equal("x2 As <anonymous type: Tuple As (c As System.Int32, System.Int32)>", model.GetDeclaredSymbol(x2).ToTestDisplayString())
End Sub
<Fact>
Public Sub OverriddenPropertyWithDifferentTupleNamesInReturn()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Property P1 As (a As Integer, b As Integer)
Public Overridable Property P2 As (a As Integer, b As Integer)
Public Overridable Property P3 As (a As Integer, b As Integer)()
Public Overridable Property P4 As (a As Integer, b As Integer)?
Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer)
End Class
Public Class Derived
Inherits Base
Public Overrides Property P1 As (a As Integer, b As Integer)
Public Overrides Property P2 As (notA As Integer, notB As Integer)
Public Overrides Property P3 As (notA As Integer, notB As Integer)()
Public Overrides Property P4 As (notA As Integer, notB As Integer)?
Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer)
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40001: 'Public Overrides Property P2 As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Property P2 As (a As Integer, b As Integer)' because they differ by their tuple element names.
Public Overrides Property P2 As (notA As Integer, notB As Integer)
~~
BC40001: 'Public Overrides Property P3 As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Property P3 As (a As Integer, b As Integer)()' because they differ by their tuple element names.
Public Overrides Property P3 As (notA As Integer, notB As Integer)()
~~
BC40001: 'Public Overrides Property P4 As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Property P4 As (a As Integer, b As Integer)?' because they differ by their tuple element names.
Public Overrides Property P4 As (notA As Integer, notB As Integer)?
~~
BC40001: 'Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names.
Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer)
~~
</errors>)
End Sub
<Fact>
Public Sub OverriddenPropertyWithNoTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Property P6 As (a As Integer, b As Integer)
End Class
Public Class Derived
Inherits Base
Public Overrides Property P6 As (Integer, Integer)
Sub M()
Dim result = Me.P6
Dim result2 = MyBase.P6
System.Console.Write(result.a)
System.Console.Write(result2.a)
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
</errors>)
Dim tree = comp.SyntaxTrees.First()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0)
Assert.Equal("Me.P6", propertyAccess.ToString())
Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString())
Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1)
Assert.Equal("MyBase.P6", propertyAccess2.ToString())
Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub OverriddenPropertyWithNoTupleNamesWithValueTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Base
Public Overridable Property P6 As (a As Integer, b As Integer)
End Class
Public Class Derived
Inherits Base
Public Overrides Property P6 As System.ValueTuple(Of Integer, Integer)
Sub M()
Dim result = Me.P6
Dim result2 = MyBase.P6
System.Console.Write(result.a)
System.Console.Write(result2.a)
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
</errors>)
Dim tree = comp.SyntaxTrees.First()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0)
Assert.Equal("Me.P6", propertyAccess.ToString())
Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString())
Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1)
Assert.Equal("MyBase.P6", propertyAccess2.ToString())
Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub OverriddenEventWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class Base
Public Overridable Event E1 As Action(Of (a As Integer, b As Integer))
End Class
Public Class Derived
Inherits Base
Public Overrides Event E1 As Action(Of (Integer, Integer))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30243: 'Overridable' is not valid on an event declaration.
Public Overridable Event E1 As Action(Of (a As Integer, b As Integer))
~~~~~~~~~~~
BC30243: 'Overrides' is not valid on an event declaration.
Public Overrides Event E1 As Action(Of (Integer, Integer))
~~~~~~~~~
BC40004: event 'E1' conflicts with event 'E1' in the base class 'Base' and should be declared 'Shadows'.
Public Overrides Event E1 As Action(Of (Integer, Integer))
~~
</errors>)
End Sub
<Fact>
Public Sub StructInStruct()
Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Public Structure S
Public Field As (S, S)
End Structure
]]></file>
</compilation>,
references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30294: Structure 'S' cannot contain an instance of itself:
'S' contains '(S, S)' (variable 'Field').
'(S, S)' contains 'S' (variable 'Item1').
Public Field As (S, S)
~~~~~
</errors>)
End Sub
<Fact>
Public Sub AssignNullWithMissingValueTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class S
Dim t As (Integer, Integer) = Nothing
End Class
</file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported.
Dim t As (Integer, Integer) = Nothing
~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub MultipleImplementsWithDifferentTupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Interface I0
Sub M(x As (a0 As Integer, b0 As Integer))
Function MR() As (a0 As Integer, b0 As Integer)
End Interface
Public Interface I1
Sub M(x As (a1 As Integer, b1 As Integer))
Function MR() As (a1 As Integer, b1 As Integer)
End Interface
Public Class C1
Implements I0, I1
Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M
End Sub
Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR
Return (1, 2)
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC30402: 'M' cannot implement sub 'M' on interface 'I0' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a0 As Integer, b0 As Integer))'.
Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M
~~~~
BC30402: 'M' cannot implement sub 'M' on interface 'I1' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a1 As Integer, b1 As Integer))'.
Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M
~~~~
BC30402: 'MR' cannot implement function 'MR' on interface 'I0' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a0 As Integer, b0 As Integer)'.
Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR
~~~~~
BC30402: 'MR' cannot implement function 'MR' on interface 'I1' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a1 As Integer, b1 As Integer)'.
Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR
~~~~~
</errors>)
End Sub
<Fact>
Public Sub MethodSignatureComparerTest()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Sub M1(x As (a As Integer, b As Integer))
End Sub
Public Sub M2(x As (a As Integer, b As Integer))
End Sub
Public Sub M3(x As (notA As Integer, notB As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1")
Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2")
Dim m3 = comp.GetMember(Of MethodSymbol)("C.M3")
Dim comparison12 = MethodSignatureComparer.DetailedCompare(m1, m2, SymbolComparisonResults.TupleNamesMismatch)
Assert.Equal(0, comparison12)
Dim comparison13 = MethodSignatureComparer.DetailedCompare(m1, m3, SymbolComparisonResults.TupleNamesMismatch)
Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13)
End Sub
<Fact>
Public Sub IsSameTypeTest()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Sub M1(x As (Integer, Integer))
End Sub
Public Sub M2(x As (a As Integer, b As Integer))
End Sub
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1")
Dim tuple1 As TypeSymbol = m1.Parameters(0).Type
Dim underlying1 As NamedTypeSymbol = tuple1.TupleUnderlyingType
Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything))
Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything))
Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything))
Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything))
Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames))
Assert.True(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames))
Assert.True(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames))
Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames))
Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.ConsiderEverything))
Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.IgnoreTupleNames))
Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2")
Dim tuple2 As TypeSymbol = m2.Parameters(0).Type
Dim underlying2 As NamedTypeSymbol = tuple2.TupleUnderlyingType
Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything))
Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything))
Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything))
Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything))
Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.True(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames))
Assert.True(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames))
Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.ConsiderEverything))
Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.ConsiderEverything))
Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds))
Assert.True(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames))
Assert.True(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames))
End Sub
<Fact>
Public Sub PropertySignatureComparer_TupleNames()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Public Property P1 As (a As Integer, b As Integer)
Public Property P2 As (a As Integer, b As Integer)
Public Property P3 As (notA As Integer, notB As Integer)
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim p1 = comp.GetMember(Of PropertySymbol)("C.P1")
Dim p2 = comp.GetMember(Of PropertySymbol)("C.P2")
Dim p3 = comp.GetMember(Of PropertySymbol)("C.P3")
Dim comparison12 = PropertySignatureComparer.DetailedCompare(p1, p2, SymbolComparisonResults.TupleNamesMismatch)
Assert.Equal(0, comparison12)
Dim comparison13 = PropertySignatureComparer.DetailedCompare(p1, p3, SymbolComparisonResults.TupleNamesMismatch)
Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13)
End Sub
<Fact>
Public Sub PropertySignatureComparer_TypeCustomModifiers()
Dim il = <![CDATA[
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class public auto ansi beforefieldinit CL1`1<T1>
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method CL1`1::.ctor
.property instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)
Test()
{
.get instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) CL1`1::get_Test()
.set instance void CL1`1::set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst))
} // end of property CL1`1::Test
.method public hidebysig newslot specialname virtual
instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)
get_Test() cil managed
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: throw
} // end of method CL1`1::get_Test
.method public hidebysig newslot specialname virtual
instance void set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) cil managed
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: throw
IL_0002: ret
} // end of method CL1`1::set_Test
} // end of class CL1`1
]]>.Value
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Public Class CL2(Of T1)
Public Property Test As T1
End Class
]]></file>
</compilation>
Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False, additionalReferences:={ValueTupleRef, SystemRuntimeFacadeRef})
comp1.AssertTheseDiagnostics()
Dim property1 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL1.Test")
Assert.Equal("Property CL1(Of T1).Test As T1 modopt(System.Runtime.CompilerServices.IsConst)", property1.ToTestDisplayString())
Dim property2 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL2.Test")
Assert.Equal("Property CL2(Of T1).Test As T1", property2.ToTestDisplayString())
Assert.False(PropertySignatureComparer.RuntimePropertySignatureComparer.Equals(property1, property2))
End Sub
<Fact>
Public Sub EventSignatureComparerTest()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Class C
Public Event E1 As Action(Of (a As Integer, b As Integer))
Public Event E2 As Action(Of (a As Integer, b As Integer))
Public Event E3 As Action(Of (notA As Integer, notB As Integer))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim e1 = comp.GetMember(Of EventSymbol)("C.E1")
Dim e2 = comp.GetMember(Of EventSymbol)("C.E2")
Dim e3 = comp.GetMember(Of EventSymbol)("C.E3")
Assert.True(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e2))
Assert.False(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e3))
End Sub
<Fact>
Public Sub OperatorOverloadingWithDifferentTupleNames()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Class B1
Shared Operator >=(x1 As (a As B1, b As B1), x2 As B1) As Boolean
Return Nothing
End Operator
Shared Operator <=(x1 As (notA As B1, notB As B1), x2 As B1) As Boolean
Return Nothing
End Operator
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact>
Public Sub Shadowing()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C0
Public Function M(x As (a As Integer, (b As Integer, c As Integer))) As (a As Integer, (b As Integer, c As Integer))
Return (1, (2, 3))
End Function
End Class
Public Class C1
Inherits C0
Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer))
Return (1, (2, 3))
End Function
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC40003: function 'M' shadows an overloadable member declared in the base class 'C0'. If you want to overload the base method, this method must be declared 'Overloads'.
Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer))
~
</errors>)
End Sub
<Fact>
Public Sub UnifyDifferentTupleName()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Interface I0(Of T1)
End Interface
Class C(Of T2)
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2))
End Class
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC32072: Cannot implement interface 'I0(Of (notA As T2, notB As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments.
Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub BC31407ERR_MultipleEventImplMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1
Event evtTest1(x As (A As Integer, B As Integer))
Event evtTest2(x As (A As Integer, notB As Integer))
End Interface
Class C1
Implements I1
Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
Dim expectedErrors1 = <errors><![CDATA[
BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest1(x As (A As Integer, B As Integer))'.
Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest2(x As (A As Integer, notB As Integer))'.
Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
BC31407: Event 'Public Event evtTest3 As I1.evtTest1EventHandler' cannot implement event 'I1.Event evtTest2(x As (A As Integer, notB As Integer))' because its delegate type does not match the delegate type of another event implemented by 'Public Event evtTest3 As I1.evtTest1EventHandler'.
Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub ImplementingEventWithDifferentTupleNames()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Event evtTest1 As Action(Of (A As Integer, B As Integer))
Event evtTest2 As Action(Of (A As Integer, notB As Integer))
End Interface
Class C1
Implements I1
Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
Dim expectedErrors1 = <errors><![CDATA[
BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'.
Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'.
Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub ImplementingEventWithNoTupleNames()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Event evtTest1 As Action(Of (A As Integer, B As Integer))
Event evtTest2 As Action(Of (A As Integer, notB As Integer))
End Interface
Class C1
Implements I1
Event evtTest3 As Action(Of (Integer, Integer)) Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
CompilationUtils.AssertNoDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub ImplementingPropertyWithDifferentTupleNames()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Property P(x As (a As Integer, b As Integer)) As Boolean
End Interface
Class C1
Implements I1
Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P
Get
Return True
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(<errors>
BC30402: 'P' cannot implement property 'P' on interface 'I1' because the tuple element names in 'Public Property P(x As (notA As Integer, notB As Integer)) As Boolean' do not match those in 'Property P(x As (a As Integer, b As Integer)) As Boolean'.
Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P
~~~~
</errors>)
End Sub
<Fact()>
Public Sub ImplementingPropertyWithNoTupleNames()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Property P(x As (a As Integer, b As Integer)) As Boolean
End Interface
Class C1
Implements I1
Property P(x As (Integer, Integer)) As Boolean Implements I1.P
Get
Return True
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
Public Sub ImplementingPropertyWithNoTupleNames2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Property P As (a As Integer, b As Integer)
End Interface
Class C1
Implements I1
Property P As (Integer, Integer) Implements I1.P
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
Public Sub ImplementingMethodWithNoTupleNames()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Sub M(x As (a As Integer, b As Integer))
Function M2 As (a As Integer, b As Integer)
End Interface
Class C1
Implements I1
Sub M(x As (Integer, Integer)) Implements I1.M
End Sub
Function M2 As (Integer, Integer) Implements I1.M2
Return (1, 2)
End Function
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact>
Public Sub BC31407ERR_MultipleEventImplMismatch3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I1
Event evtTest1 As Action(Of (A As Integer, B As Integer))
Event evtTest2 As Action(Of (A As Integer, notB As Integer))
End Interface
Class C1
Implements I1
Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation1.AssertTheseDiagnostics(
<errors>
BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'.
Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'.
Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct0()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
Dim x as (a As Integer, b As String)
x.Item1 = 1
x.b = "2"
' by the language rules tuple x is definitely assigned
' since all its elements are definitely assigned
System.Console.WriteLine(x)
end sub
end class
namespace System
public class ValueTuple(Of T1, T2)
public Item1 as T1
public Item2 as T2
public Sub New(item1 as T1 , item2 as T2 )
Me.Item1 = item1
Me.Item2 = item2
end sub
End class
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
Dim x as (a As Integer, b As String)
~
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct1()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
Dim x = (1,2,3,4,5,6,7,8,9)
System.Console.WriteLine(x)
end sub
end class
namespace System
public class ValueTuple(Of T1, T2)
public Item1 as T1
public Item2 as T2
public Sub New(item1 as T1 , item2 as T2 )
Me.Item1 = item1
Me.Item2 = item2
end sub
End class
public class ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)
public Item1 As T1
public Item2 As T2
public Item3 As T3
public Item4 As T4
public Item5 As T5
public Item6 As T6
public Item7 As T7
public Rest As TRest
public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest)
Item1 = item1
Item2 = item2
Item3 = item3
Item4 = item4
Item5 = item5
Item6 = item6
Item7 = item7
Rest = rest
end Sub
End Class
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
Dim x = (1,2,3,4,5,6,7,8,9)
~
BC37281: Predefined type 'ValueTuple`8' must be a structure.
Dim x = (1,2,3,4,5,6,7,8,9)
~
</errors>)
End Sub
<Fact>
Public Sub ConversionToBase()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class Base(Of T)
End Class
Public Class Derived
Inherits Base(Of (a As Integer, b As Integer))
Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer))
Return Nothing
End Operator
Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived
Return Nothing
End Operator
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
compilation1.AssertTheseDiagnostics(
<errors>
BC33026: Conversion operators cannot convert from a type to its base type.
Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer))
~~~~~
BC33030: Conversion operators cannot convert from a base type.
Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived
~~~~~
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
end sub
Shared Sub Test2(arg as (a As Integer, b As Integer))
End Sub
end class
namespace System
public class ValueTuple(Of T1, T2)
public Item1 as T1
public Item2 as T2
public Sub New(item1 as T1 , item2 as T2 )
Me.Item1 = item1
Me.Item2 = item2
end sub
End class
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct2i()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
end sub
Shared Sub Test2(arg as (a As Integer, b As Integer))
End Sub
end class
namespace System
public interface ValueTuple(Of T1, T2)
End Interface
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct3()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
Dim x as (a As Integer, b As String)() = Nothing
' by the language rules tuple x is definitely assigned
' since all its elements are definitely assigned
System.Console.WriteLine(x)
end sub
end class
namespace System
public class ValueTuple(Of T1, T2)
public Item1 as T1
public Item2 as T2
public Sub New(item1 as T1 , item2 as T2 )
Me.Item1 = item1
Me.Item2 = item2
end sub
End class
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
Dim x as (a As Integer, b As String)() = Nothing
~
</errors>)
End Sub
<WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")>
<Fact>
Public Sub ValueTupleNotStruct4()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Tuples">
<file name="a.vb">
class C
Shared Sub Main()
end sub
Shared Function Test2()as (a As Integer, b As Integer)
End Function
end class
namespace System
public class ValueTuple(Of T1, T2)
public Item1 as T1
public Item2 as T2
public Sub New(item1 as T1 , item2 as T2 )
Me.Item1 = item1
Me.Item2 = item2
end sub
End class
end Namespace
<%= s_tupleattributes %>
</file>
</compilation>,
options:=TestOptions.DebugExe)
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
Shared Function Test2()as (a As Integer, b As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub ValueTupleBaseError_NoSystemRuntime()
Dim comp = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Function F() As ((Integer, Integer), (Integer, Integer))
End Interface
</file>
</compilation>,
references:={ValueTupleRef})
comp.AssertTheseEmitDiagnostics(
<errors>
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
Function F() As ((Integer, Integer), (Integer, Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
Function F() As ((Integer, Integer), (Integer, Integer))
~~~~~~~~~~~~~~~~~~
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
Function F() As ((Integer, Integer), (Integer, Integer))
~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")>
<Fact>
Public Sub ValueTupleBaseError_MissingReference()
Dim comp0 = CreateCompilationWithMscorlib40(
<compilation name="5a03232e-1a0f-4d1b-99ba-5d7b40ea931e">
<file name="a.vb">
Public Class A
End Class
Public Class B
End Class
</file>
</compilation>)
comp0.AssertNoDiagnostics()
Dim ref0 = comp0.EmitToImageReference()
Dim comp1 = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Public Class C(Of T)
End Class
Namespace System
Public Class ValueTuple(Of T1, T2)
Inherits A
Public Sub New(_1 As T1, _2 As T2)
End Sub
End Class
Public Class ValueTuple(Of T1, T2, T3)
Inherits C(Of B)
Public Sub New(_1 As T1, _2 As T2, _3 As T3)
End Sub
End Class
End Namespace
</file>
</compilation>,
references:={ref0})
Dim ref1 = comp1.EmitToImageReference()
Dim comp = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Function F() As (Integer, (Integer, Integer), (Integer, Integer))
End Interface
</file>
</compilation>,
references:={ref1})
comp.AssertTheseEmitDiagnostics(
<errors>
BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project.
BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'B'. Add one to your project.
</errors>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub ValueTupleBase_AssemblyUnification()
Dim signedDllOptions = TestOptions.SigningReleaseDll.
WithCryptoKeyFile(SigningTestHelpers.KeyPairFile)
Dim comp0v1 = CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
<Assembly: System.Reflection.AssemblyVersion("1.0.0.0")>
Public Class A
End Class
]]></file>
</compilation>,
options:=signedDllOptions)
comp0v1.AssertNoDiagnostics()
Dim ref0v1 = comp0v1.EmitToImageReference()
Dim comp0v2 = CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
<Assembly: System.Reflection.AssemblyVersion("2.0.0.0")>
Public Class A
End Class
]]></file>
</compilation>,
options:=signedDllOptions)
comp0v2.AssertNoDiagnostics()
Dim ref0v2 = comp0v2.EmitToImageReference()
Dim comp1 = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Public Class B
Inherits A
End Class
</file>
</compilation>,
references:={ref0v1})
comp1.AssertNoDiagnostics()
Dim ref1 = comp1.EmitToImageReference()
Dim comp2 = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Namespace System
Public Class ValueTuple(Of T1, T2)
Inherits B
Public Sub New(_1 As T1, _2 As T2)
End Sub
End Class
End Namespace
</file>
</compilation>,
references:={ref0v1, ref1})
Dim ref2 = comp2.EmitToImageReference()
Dim comp = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Function F() As (Integer, Integer)
End Interface
</file>
</compilation>,
references:={ref0v2, ref1, ref2})
comp.AssertTheseEmitDiagnostics(
<errors>
BC37281: Predefined type 'ValueTuple`2' must be a structure.
</errors>)
End Sub
<Fact>
Public Sub TernaryTypeInferenceWithDynamicAndTupleNames()
' No dynamic in VB
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim flag As Boolean = True
Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3))
System.Console.Write(x1.a)
End Sub
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3))
~~~~
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3))
~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0)
Dim x1Symbol = model.GetDeclaredSymbol(x1)
Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(16825, "https://github.com/dotnet/roslyn/issues/16825")>
Public Sub NullCoalescingOperatorWithTupleNames()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim nab As (a As Integer, b As Integer)? = (1, 2)
Dim nac As (a As Integer, c As Integer)? = (1, 3)
Dim x1 = If(nab, nac) ' (a, )?
Dim x2 = If(nab, nac.Value) ' (a, )
Dim x3 = If(new C(), nac) ' C
Dim x4 = If(new D(), nac) ' (a, c)?
Dim x5 = If(nab IsNot Nothing, nab, nac) ' (a, )?
Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, )
Dim x7 = If(nab, (a:= 1, 3)) ' (a, )
Dim x8 = If(new C(), (a:= 1, c:= 3)) ' C
Dim x9 = If(new D(), (a:= 1, c:= 3)) ' (a, c)
Dim x6double = If(nab, (d:= 1.1, c:= 3)) ' (d, c)
End Sub
Public Shared Narrowing Operator CType(ByVal x As (Integer, Integer)) As C
Throw New System.Exception()
End Operator
End Class
Class D
Public Shared Narrowing Operator CType(ByVal x As D) As (d1 As Integer, d2 As Integer)
Throw New System.Exception()
End Operator
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, )
~~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0)
Assert.Equal("x1 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x1).ToTestDisplayString())
Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(3).Names(0)
Assert.Equal("x2 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x2).ToTestDisplayString())
Dim x3 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(4).Names(0)
Assert.Equal("x3 As C", model.GetDeclaredSymbol(x3).ToTestDisplayString())
Dim x4 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(5).Names(0)
Assert.Equal("x4 As System.Nullable(Of (a As System.Int32, c As System.Int32))", model.GetDeclaredSymbol(x4).ToTestDisplayString())
Dim x5 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(6).Names(0)
Assert.Equal("x5 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x5).ToTestDisplayString())
Dim x6 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(7).Names(0)
Assert.Equal("x6 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x6).ToTestDisplayString())
Dim x7 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(8).Names(0)
Assert.Equal("x7 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x7).ToTestDisplayString())
Dim x8 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(9).Names(0)
Assert.Equal("x8 As C", model.GetDeclaredSymbol(x8).ToTestDisplayString())
Dim x9 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(10).Names(0)
Assert.Equal("x9 As (a As System.Int32, c As System.Int32)", model.GetDeclaredSymbol(x9).ToTestDisplayString())
Dim x6double = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(11).Names(0)
Assert.Equal("x6double As (d As System.Double, c As System.Int32)", model.GetDeclaredSymbol(x6double).ToTestDisplayString())
End Sub
<Fact>
Public Sub TernaryTypeInferenceWithNoNames()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim flag As Boolean = True
Dim x1 = If(flag, (a:=1, b:=2), (1, 3))
Dim x2 = If(flag, (1, 2), (a:=1, b:=3))
End Sub
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
Dim x1 = If(flag, (a:=1, b:=2), (1, 3))
~~~~
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
Dim x1 = If(flag, (a:=1, b:=2), (1, 3))
~~~~
BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
Dim x2 = If(flag, (1, 2), (a:=1, b:=3))
~~~~
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
Dim x2 = If(flag, (1, 2), (a:=1, b:=3))
~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0)
Dim x1Symbol = model.GetDeclaredSymbol(x1)
Assert.Equal("x1 As (System.Int32, System.Int32)", x1Symbol.ToTestDisplayString())
Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(2).First().Names(0)
Dim x2Symbol = model.GetDeclaredSymbol(x2)
Assert.Equal("x2 As (System.Int32, System.Int32)", x2Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub TernaryTypeInferenceDropsCandidates()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim flag As Boolean = True
Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3))
End Sub
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Long)'.
Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3))
~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0)
Dim x1Symbol = model.GetDeclaredSymbol(x1)
Assert.Equal("x1 As (a As System.Int32, b As System.Int64)", x1Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub LambdaTypeInferenceWithTupleNames()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim x1 = M2(Function()
Dim flag = True
If flag Then
Return (a:=1, b:=2)
Else
If flag Then
Return (a:=1, c:=3)
Else
Return (a:=1, d:=4)
End If
End If
End Function)
End Sub
Function M2(Of T)(f As System.Func(Of T)) As T
Return f()
End Function
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Return (a:=1, b:=2)
~~~~
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Return (a:=1, c:=3)
~~~~
BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Return (a:=1, d:=4)
~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Dim x1Symbol = model.GetDeclaredSymbol(x1)
Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub LambdaTypeInferenceFallsBackToObject()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim x1 = M2(Function()
Dim flag = True
Dim l1 = CType(2, Long)
If flag Then
Return (a:=1, b:=l1)
Else
If flag Then
Return (a:=l1, c:=3)
Else
Return (a:=1, d:=l1)
End If
End If
End Function)
End Sub
Function M2(Of T)(f As System.Func(Of T)) As T
Return f()
End Function
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0)
Dim x1Symbol = model.GetDeclaredSymbol(x1)
Assert.Equal("x1 As System.Object", x1Symbol.ToTestDisplayString())
End Sub
<Fact>
Public Sub IsBaseOf_WithoutCustomModifiers()
' The IL is from this code, but with modifiers
' public class Base<T> { }
' public class Derived<T> : Base<T> { }
' public class Test
' {
' public Base<Object> GetBaseWithModifiers() { return null; }
' public Derived<Object> GetDerivedWithoutModifiers() { return null; }
' }
Dim il = <![CDATA[
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class public auto ansi beforefieldinit Base`1<T>
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2050
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Base`1::.ctor
} // end of class Base`1
.class public auto ansi beforefieldinit Derived`1<T>
extends class Base`1<!T>
{
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2059
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void class Base`1<!T>::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Derived`1::.ctor
} // end of class Derived`1
.class public auto ansi beforefieldinit Test
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> GetBaseWithModifiers () cil managed
{
// Method begins at RVA 0x2064
// Code size 7 (0x7)
.maxstack 1
.locals init (
[0] class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
)
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
} // end of method Test::GetBaseWithModifiers
.method public hidebysig
instance class Derived`1<object> GetDerivedWithoutModifiers () cil managed
{
// Method begins at RVA 0x2078
// Code size 7 (0x7)
.maxstack 1
.locals init (
[0] class Derived`1<object>
)
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
} // end of method Test::GetDerivedWithoutModifiers
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2050
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Test::.ctor
} // end of class Test
]]>.Value
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
]]></file>
</compilation>
Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False)
comp1.AssertTheseDiagnostics()
Dim baseWithModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetBaseWithModifiers").ReturnType
Assert.Equal("Base(Of System.Object modopt(System.Runtime.CompilerServices.IsLong))", baseWithModifiers.ToTestDisplayString())
Dim derivedWithoutModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetDerivedWithoutModifiers").ReturnType
Assert.Equal("Derived(Of System.Object)", derivedWithoutModifiers.ToTestDisplayString())
Dim diagnostics = New HashSet(Of DiagnosticInfo)()
Assert.True(baseWithModifiers.IsBaseTypeOf(derivedWithoutModifiers, diagnostics))
Assert.True(derivedWithoutModifiers.IsOrDerivedFrom(derivedWithoutModifiers, diagnostics))
End Sub
<Fact>
Public Sub WarnForDroppingNamesInConversion()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim x1 As (a As Integer, Integer) = (1, b:=2)
Dim x2 As (a As Integer, String) = (1, b:=Nothing)
End Sub
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim x1 As (a As Integer, Integer) = (1, b:=2)
~~~~
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, String)'.
Dim x2 As (a As Integer, String) = (1, b:=Nothing)
~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub MethodTypeInferenceMergesTupleNames()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim t = M2((a:=1, b:=2), (a:=1, c:=3))
System.Console.Write(t.a)
System.Console.Write(t.b)
System.Console.Write(t.c)
M2((1, 2), (c:=1, d:=3))
M2({(a:=1, b:=2)}, {(1, 3)})
End Sub
Function M2(Of T)(x1 As T, x2 As T) As T
Return x1
End Function
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim t = M2((a:=1, b:=2), (a:=1, c:=3))
~~~~
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'.
Dim t = M2((a:=1, b:=2), (a:=1, c:=3))
~~~~
BC30456: 'b' is not a member of '(a As Integer, Integer)'.
System.Console.Write(t.b)
~~~
BC30456: 'c' is not a member of '(a As Integer, Integer)'.
System.Console.Write(t.c)
~~~
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
M2((1, 2), (c:=1, d:=3))
~~~~
BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'.
M2((1, 2), (c:=1, d:=3))
~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First())
Assert.Equal("(a As System.Int32, System.Int32)",
DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(4).First())
Assert.Equal("(System.Int32, System.Int32)",
DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(5).First())
Assert.Equal("(a As System.Int32, b As System.Int32)()",
DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
End Sub
<Fact>
Public Sub MethodTypeInferenceDropsCandidates()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Tuples">
<file name="a.vb"><![CDATA[
Class C
Sub M()
M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte)))
M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte)))
M2((a:=CType(1, Long), b:=2), (CType(1, Byte), 3))
End Sub
Function M2(Of T)(x1 As T, x2 As T) As T
Return x1
End Function
End Class
]]></file>
</compilation>, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Integer)'.
M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte)))
~~~~~~~~~~~~~~~~~
BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'.
M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte)))
~~~~
BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'.
M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte)))
~~~~~~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First())
Assert.Equal("(a As System.Int32, b As System.Int32)",
DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(1).First())
Assert.Equal("(System.Int64, b As System.Int32)",
DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(2).First())
Assert.Equal("(a As System.Int64, b As System.Int32)",
DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString())
End Sub
<Fact()>
<WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")>
Public Sub NoSystemRuntimeFacade()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim o = (1, 2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef})
Assert.Equal(TypeKind.Class, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).TypeKind)
comp.AssertTheseDiagnostics(
<errors>
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
Dim o = (1, 2)
~~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")>
Public Sub Iterator_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Public Class C
Shared Sub Main()
For Each x in Test()
Console.WriteLine(x)
Next
End Sub
Shared Iterator Function Test() As IEnumerable(Of (integer, integer))
yield (1, 2)
End Function
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(1, 2)")
End Sub
<Fact()>
<WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")>
Public Sub Iterator_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Public Class C
Iterator Function Test() As IEnumerable(Of (integer, integer))
yield (1, 2)
End Function
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef})
comp.AssertTheseEmitDiagnostics(
<errors>
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
Iterator Function Test() As IEnumerable(Of (integer, integer))
~~~~~~~~~~~~~~~~~~
BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project.
yield (1, 2)
~~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_01()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((X1:=1, Y1:=2))
Dim t1 = (X1:=3, Y1:=4)
Test(t1)
Test((5, 6))
Dim t2 = (7, 8)
Test(t2)
End Sub
Shared Sub Test(val As AA)
End Sub
End Class
Public Class AA
Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA
System.Console.WriteLine(x)
return new AA()
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
(1, 2)
(3, 4)
(5, 6)
(7, 8)
")
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_02()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test((X1:=1, Y1:=2))
Dim t1 = (X1:=3, Y1:=4)
Test(t1)
Test((5, 6))
Dim t2 = (7, 8)
Test(t2)
End Sub
Shared Sub Test(val As AA?)
End Sub
End Class
Public Structure AA
Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA
System.Console.WriteLine(x)
return new AA()
End Operator
End Structure
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
(1, 2)
(3, 4)
(5, 6)
(7, 8)
")
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_03()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim t1 As (X1 as Integer, Y1 as Integer)? = (X1:=3, Y1:=4)
Test(t1)
Dim t2 As (Integer, Integer)? = (7, 8)
Test(t2)
System.Console.WriteLine("--")
t1 = Nothing
Test(t1)
t2 = Nothing
Test(t2)
System.Console.WriteLine("--")
End Sub
Shared Sub Test(val As AA?)
End Sub
End Class
Public Structure AA
Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA
System.Console.WriteLine(x)
return new AA()
End Operator
End Structure
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
(3, 4)
(7, 8)
--
--
")
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_04()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test(new AA())
End Sub
Shared Sub Test(val As (X1 As Integer, Y1 As Integer))
System.Console.WriteLine(val)
End Sub
End Class
Public Class AA
Public Shared Widening Operator CType(x As AA) As (Integer, Integer)
return (1, 2)
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(1, 2)")
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_05()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Test(new AA())
End Sub
Shared Sub Test(val As (X1 As Integer, Y1 As Integer))
System.Console.WriteLine(val)
End Sub
End Class
Public Class AA
Public Shared Widening Operator CType(x As AA) As (X1 As Integer, Y1 As Integer)
return (1, 2)
End Operator
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(1, 2)")
End Sub
<Fact>
<WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")>
Public Sub UserDefinedConversionsAndNameMismatch_06()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C
Shared Sub Main()
Dim t1 As BB(Of (X1 as Integer, Y1 as Integer))? = New BB(Of (X1 as Integer, Y1 as Integer))()
Test(t1)
Dim t2 As BB(Of (Integer, Integer))? = New BB(Of (Integer, Integer))()
Test(t2)
System.Console.WriteLine("--")
t1 = Nothing
Test(t1)
t2 = Nothing
Test(t2)
System.Console.WriteLine("--")
End Sub
Shared Sub Test(val As AA?)
End Sub
End Class
Public Structure AA
Public Shared Widening Operator CType(x As BB(Of (X1 As Integer, Y1 As Integer))) As AA
System.Console.WriteLine("implicit operator AA")
return new AA()
End Operator
End Structure
Public Structure BB(Of T)
End Structure
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="
implicit operator AA
implicit operator AA
--
--
")
End Sub
<Fact>
Public Sub GenericConstraintAttributes()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports ClassLibrary4
Public Interface ITest(Of T)
ReadOnly Property [Get] As T
End Interface
Public Class Test
Implements ITest(Of (key As Integer, val As Integer))
Public ReadOnly Property [Get] As (key As Integer, val As Integer) Implements ITest(Of (key As Integer, val As Integer)).Get
Get
Return (0, 0)
End Get
End Property
End Class
Public Class Base(Of T) : Implements ITest(Of T)
Public ReadOnly Property [Get] As T Implements ITest(Of T).Get
Protected Sub New(t As T)
[Get] = t
End Sub
End Class
Public Class C(Of T As ITest(Of (key As Integer, val As Integer)))
Public ReadOnly Property [Get] As T
Public Sub New(t As T)
[Get] = t
End Sub
End Class
Public Class C2(Of T As Base(Of (key As Integer, val As Integer)))
Public ReadOnly Property [Get] As T
Public Sub New(t As T)
[Get] = t
End Sub
End Class
Public NotInheritable Class Test2
Inherits Base(Of (key As Integer, val As Integer))
Sub New()
MyBase.New((-1, -2))
End Sub
End Class
Public Class C3(Of T As IEnumerable(Of (key As Integer, val As Integer)))
Public ReadOnly Property [Get] As T
Public Sub New(t As T)
[Get] = t
End Sub
End Class
Public Structure TestEnumerable
Implements IEnumerable(Of (key As Integer, val As Integer))
Private ReadOnly _backing As (Integer, Integer)()
Public Sub New(backing As (Integer, Integer)())
_backing = backing
End Sub
Private Class Inner
Implements IEnumerator(Of (key As Integer, val As Integer)), IEnumerator
Private index As Integer = -1
Private ReadOnly _backing As (Integer, Integer)()
Public Sub New(backing As (Integer, Integer)())
_backing = backing
End Sub
Public ReadOnly Property Current As (key As Integer, val As Integer) Implements IEnumerator(Of (key As Integer, val As Integer)).Current
Get
Return _backing(index)
End Get
End Property
Public ReadOnly Property Current1 As Object Implements IEnumerator.Current
Get
Return Current
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Function MoveNext() As Boolean
index += 1
Return index < _backing.Length
End Function
Public Sub Reset()
Throw New NotSupportedException()
End Sub
Private Function IEnumerator_MoveNext() As Boolean Implements IEnumerator.MoveNext
Return MoveNext()
End Function
Private Sub IEnumerator_Reset() Implements IEnumerator.Reset
Throw New NotImplementedException()
End Sub
End Class
Public Function GetEnumerator() As IEnumerator(Of (key As Integer, val As Integer)) Implements IEnumerable(Of (key As Integer, val As Integer)).GetEnumerator
Return New Inner(_backing)
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return New Inner(_backing)
End Function
End Structure
</file>
</compilation>,
additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, symbolValidator:=Sub(m)
Dim c = m.GlobalNamespace.GetTypeMember("C")
Assert.Equal(1, c.TypeParameters.Length)
Dim param = c.TypeParameters(0)
Assert.Equal(1, param.ConstraintTypes.Length)
Dim constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0))
Assert.True(constraint.IsGenericType)
Assert.Equal(1, constraint.TypeArguments.Length)
Dim typeArg As TypeSymbol = constraint.TypeArguments(0)
Assert.True(typeArg.IsTupleType)
Assert.Equal(2, typeArg.TupleElementTypes.Length)
Assert.All(typeArg.TupleElementTypes,
Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType))
Assert.False(typeArg.TupleElementNames.IsDefault)
Assert.Equal(2, typeArg.TupleElementNames.Length)
Assert.Equal({"key", "val"}, typeArg.TupleElementNames)
Dim c2 = m.GlobalNamespace.GetTypeMember("C2")
Assert.Equal(1, c2.TypeParameters.Length)
param = c2.TypeParameters(0)
Assert.Equal(1, param.ConstraintTypes.Length)
constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0))
Assert.True(constraint.IsGenericType)
Assert.Equal(1, constraint.TypeArguments.Length)
typeArg = constraint.TypeArguments(0)
Assert.True(typeArg.IsTupleType)
Assert.Equal(2, typeArg.TupleElementTypes.Length)
Assert.All(typeArg.TupleElementTypes,
Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType))
Assert.False(typeArg.TupleElementNames.IsDefault)
Assert.Equal(2, typeArg.TupleElementNames.Length)
Assert.Equal({"key", "val"}, typeArg.TupleElementNames)
End Sub
)
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim c = New C(Of Test)(New Test())
Dim temp = c.Get.Get
Console.WriteLine(temp)
Console.WriteLine("key: " & temp.key)
Console.WriteLine("val: " & temp.val)
Dim c2 = New C2(Of Test2)(New Test2())
Dim temp2 = c2.Get.Get
Console.WriteLine(temp2)
Console.WriteLine("key: " & temp2.key)
Console.WriteLine("val: " & temp2.val)
Dim backing = {(1, 2), (3, 4), (5, 6)}
Dim c3 = New C3(Of TestEnumerable)(New TestEnumerable(backing))
For Each kvp In c3.Get
Console.WriteLine($"key: {kvp.key}, val: {kvp.val}")
Next
Dim c4 = New C(Of Test2)(New Test2())
Dim temp4 = c4.Get.Get
Console.WriteLine(temp4)
Console.WriteLine("key: " & temp4.key)
Console.WriteLine("val: " & temp4.val)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs.Concat({comp.EmitToImageReference()}).ToArray(), expectedOutput:=<![CDATA[
(0, 0)
key: 0
val: 0
(-1, -2)
key: -1
val: -2
key: 1, val: 2
key: 3, val: 4
key: 5, val: 6
(-1, -2)
key: -1
val: -2
]]>)
End Sub
<Fact>
Public Sub UnusedTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Sub M()
' Warnings
Dim x2 As Integer
Const x3 As Integer = 1
Const x4 As String = "hello"
Dim x5 As (Integer, Integer)
Dim x6 As (String, String)
' No warnings
Dim y10 As Integer = 1
Dim y11 As String = "hello"
Dim y12 As (Integer, Integer) = (1, 2)
Dim y13 As (String, String) = ("hello", "world")
Dim tuple As (String, String) = ("hello", "world")
Dim y14 As (String, String) = tuple
Dim y15 = (2, 3)
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<errors>
BC42024: Unused local variable: 'x2'.
Dim x2 As Integer
~~
BC42099: Unused local constant: 'x3'.
Const x3 As Integer = 1
~~
BC42099: Unused local constant: 'x4'.
Const x4 As String = "hello"
~~
BC42024: Unused local variable: 'x5'.
Dim x5 As (Integer, Integer)
~~
BC42024: Unused local variable: 'x6'.
Dim x6 As (String, String)
~~
</errors>)
End Sub
<Fact>
<WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")>
Public Sub TuplePropertyArgs001()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Public Class C
Shared Sub Main()
dim inst = new C
dim f As (Integer, Integer) = (inst.P1, inst.P1)
System.Console.WriteLine(f)
End Sub
public readonly Property P1 as integer
Get
return 42
End Get
end Property
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(42, 42)")
End Sub
<Fact>
<WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")>
Public Sub TuplePropertyArgs002()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Public Class C
Shared Sub Main()
dim inst = new C
dim f As IComparable(of (Integer, Integer)) = (inst.P1, inst.P1)
System.Console.WriteLine(f)
End Sub
public readonly Property P1 as integer
Get
return 42
End Get
end Property
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(42, 42)")
End Sub
<Fact>
<WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")>
Public Sub TuplePropertyArgs003()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Public Class C
Shared Sub Main()
dim inst as Object = new C
dim f As (Integer, Integer) = (inst.P1, inst.P1)
System.Console.WriteLine(f)
End Sub
public readonly Property P1 as integer
Get
return 42
End Get
end Property
End Class
</file>
</compilation>,
options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs)
CompileAndVerify(comp, expectedOutput:="(42, 42)")
End Sub
<Fact>
<WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")>
Public Sub InterfaceImplAttributesAreNotSharedAcrossTypeRefs()
Dim src1 = <compilation>
<file name="a.vb">
<![CDATA[
Public Interface I1(Of T)
End Interface
Public Interface I2
Inherits I1(Of (a As Integer, b As Integer))
End Interface
Public Interface I3
Inherits I1(Of (c As Integer, d As Integer))
End Interface
]]>
</file>
</compilation>
Dim src2 = <compilation>
<file name="a.vb">
<![CDATA[
Class C1
Implements I2
Implements I1(Of (a As Integer, b As Integer))
End Class
Class C2
Implements I3
Implements I1(Of (c As Integer, d As Integer))
End Class
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40(src1, references:=s_valueTupleRefs)
AssertTheseDiagnostics(comp1)
Dim comp2 = CreateCompilationWithMscorlib40(src2,
references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.ToMetadataReference()})
AssertTheseDiagnostics(comp2)
Dim comp3 = CreateCompilationWithMscorlib40(src2,
references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.EmitToImageReference()})
AssertTheseDiagnostics(comp3)
End Sub
<Fact()>
<WorkItem(14881, "https://github.com/dotnet/roslyn/issues/14881")>
<WorkItem(15476, "https://github.com/dotnet/roslyn/issues/15476")>
Public Sub TupleElementVsLocal()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim tuple As (Integer, elem2 As Integer)
Dim elem2 As Integer
tuple = (5, 6)
tuple.elem2 = 23
elem2 = 10
Console.WriteLine(tuple.elem2)
Console.WriteLine(elem2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "elem2").ToArray()
Assert.Equal(4, nodes.Length)
Assert.Equal("tuple.elem2 = 23", nodes(0).Parent.Parent.ToString())
Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(0)).Symbol.ToTestDisplayString())
Assert.Equal("elem2 = 10", nodes(1).Parent.ToString())
Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(1)).Symbol.ToTestDisplayString())
Assert.Equal("(tuple.elem2)", nodes(2).Parent.Parent.Parent.ToString())
Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(2)).Symbol.ToTestDisplayString())
Assert.Equal("(elem2)", nodes(3).Parent.Parent.ToString())
Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(3)).Symbol.ToTestDisplayString())
Dim type = tree.GetRoot().DescendantNodes().OfType(Of TupleTypeSyntax)().Single()
Dim symbolInfo = model.GetSymbolInfo(type)
Assert.Equal("(System.Int32, elem2 As System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Dim typeInfo = model.GetTypeInfo(type)
Assert.Equal("(System.Int32, elem2 As System.Int32)", typeInfo.Type.ToTestDisplayString())
Assert.Same(symbolInfo.Symbol, typeInfo.Type)
Assert.Equal(SyntaxKind.TypedTupleElement, type.Elements.First().Kind())
Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(type.Elements.First()).ToTestDisplayString())
Assert.Equal(SyntaxKind.NamedTupleElement, type.Elements.Last().Kind())
Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(type.Elements.Last()).ToTestDisplayString())
Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.First(), SyntaxNode)).ToTestDisplayString())
Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.Last(), SyntaxNode)).ToTestDisplayString())
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ImplementSameInterfaceViaBaseWithDifferentTupleNames()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface ITest(Of T)
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
Class Derived
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1)
Dim derivedSymbol = model.GetDeclaredSymbol(derived)
Assert.Equal("Derived", derivedSymbol.ToTestDisplayString())
Assert.Equal(New String() {
"ITest(Of (a As System.Int32, b As System.Int32))",
"ITest(Of (notA As System.Int32, notB As System.Int32))"},
derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ImplementSameInterfaceViaBase()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface ITest(Of T)
End Interface
Class Base
Implements ITest(Of Integer)
End Class
Class Derived
Inherits Base
Implements ITest(Of Integer)
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1)
Dim derivedSymbol = model.GetDeclaredSymbol(derived)
Assert.Equal("Derived", derivedSymbol.ToTestDisplayString())
Assert.Equal(New String() {"ITest(Of System.Int32)"},
derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub GenericImplementSameInterfaceViaBaseWithoutTuples()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface ITest(Of T)
End Interface
Class Base
Implements ITest(Of Integer)
End Class
Class Derived(Of T)
Inherits Base
Implements ITest(Of T)
End Class
Module M
Sub Main()
Dim instance1 = New Derived(Of Integer)
Dim instance2 = New Derived(Of String)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1)
Dim derivedSymbol = DirectCast(model.GetDeclaredSymbol(derived), NamedTypeSymbol)
Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString())
Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of T)"},
derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0)
Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type
Assert.Equal("Derived(Of Integer)", instance1Symbol.ToString())
Assert.Equal(New String() {"ITest(Of System.Int32)"},
instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0)
Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type
Assert.Equal("Derived(Of String)", instance2Symbol.ToString())
Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of System.String)"},
instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
Assert.Empty(derivedSymbol.AsUnboundGenericType().AllInterfaces)
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub GenericImplementSameInterfaceViaBase()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface ITest(Of T)
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
Class Derived(Of T)
Inherits Base
Implements ITest(Of T)
End Class
Module M
Sub Main()
Dim instance1 = New Derived(Of (notA As Integer, notB As Integer))
Dim instance2 = New Derived(Of (notA As String, notB As String))
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.First()
Dim model = compilation.GetSemanticModel(tree)
Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1)
Dim derivedSymbol = model.GetDeclaredSymbol(derived)
Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString())
Assert.Equal(New String() {"ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of T)"},
derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0)
Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type
Assert.Equal("Derived(Of (notA As Integer, notB As Integer))", instance1Symbol.ToString())
Assert.Equal(New String() {
"ITest(Of (a As System.Int32, b As System.Int32))",
"ITest(Of (notA As System.Int32, notB As System.Int32))"},
instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0)
Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type
Assert.Equal("Derived(Of (notA As String, notB As String))", instance2Symbol.ToString())
Assert.Equal(New String() {
"ITest(Of (a As System.Int32, b As System.Int32))",
"ITest(Of (notA As System.String, notB As System.String))"},
instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString()))
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Base
Implements IEnumerable(Of (a As Integer, b As Integer))
Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New Exception()
End Function
Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator
Throw New Exception()
End Function
End Class
Class Derived(Of T)
Inherits Base
Implements IEnumerable(Of T)
Public Dim state As T
Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New Exception()
End Function
Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
Return New DerivedEnumerator With {.state = state}
End Function
Public Class DerivedEnumerator
Implements IEnumerator(Of T)
Public Dim state As T
Dim done As Boolean = False
Function MoveNext() As Boolean Implements IEnumerator.MoveNext
If done Then
Return False
Else
done = True
Return True
End If
End Function
ReadOnly Property Current As T Implements IEnumerator(Of T).Current
Get
Return state
End Get
End Property
ReadOnly Property Current2 As Object Implements IEnumerator.Current
Get
Throw New Exception()
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Sub Reset() Implements IEnumerator.Reset
End Sub
End Class
End Class
Module M
Sub Main()
Dim collection = New Derived(Of (notA As String, notB As String)) With {.state = (42, 43)}
For Each x In collection
Console.Write(x.notA)
Next
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
compilation.AssertTheseDiagnostics(<errors>
BC32096: 'For Each' on type 'Derived(Of (notA As String, notB As String))' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.
For Each x In collection
~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTupleNames()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Base
Implements IEnumerable(Of (a As Integer, b As Integer))
Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New Exception()
End Function
Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator
Throw New Exception()
End Function
End Class
Class Derived(Of T)
Inherits Base
Implements IEnumerable(Of T)
Public Dim state As T
Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New Exception()
End Function
Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
Return New DerivedEnumerator With {.state = state}
End Function
Public Class DerivedEnumerator
Implements IEnumerator(Of T)
Public Dim state As T
Dim done As Boolean = False
Function MoveNext() As Boolean Implements IEnumerator.MoveNext
If done Then
Return False
Else
done = True
Return True
End If
End Function
ReadOnly Property Current As T Implements IEnumerator(Of T).Current
Get
Return state
End Get
End Property
ReadOnly Property Current2 As Object Implements IEnumerator.Current
Get
Throw New Exception()
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Sub Reset() Implements IEnumerator.Reset
End Sub
End Class
End Class
Module M
Sub Main()
Dim collection = New Derived(Of (notA As Integer, notB As Integer)) With {.state = (42, 43)}
For Each x In collection
Console.Write(x.notA)
Next
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
compilation.AssertTheseDiagnostics()
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<Fact()>
<WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")>
Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1(Of T)
End Interface
Class Base(Of U As I1(Of (a As Integer, b As Integer)))
End Class
Class Derived
Inherits Base(Of I1(Of (notA As Integer, notB As Integer)))
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
<WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")>
Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1(Of T)
End Interface
Interface I2(Of T)
Inherits I1(Of T)
End Interface
Class Base(Of U As I1(Of (a As Integer, b As Integer)))
End Class
Class Derived
Inherits Base(Of I2(Of (notA As Integer, notB As Integer)))
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub CanReImplementInterfaceWithDifferentTupleNames()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ITest(Of T)
Function M() As T
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M
Return (1, 2)
End Function
End Class
Class Derived
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M
Return (3, 4)
End Function
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_01()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ITest(Of T)
Function M() As T
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M
Return (1, 2)
End Function
End Class
Class Derived1
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
Class Derived2
Inherits Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(<errors>
BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'.
Implements ITest(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_02()
Dim csSource = "
public interface ITest<T>
{
T M();
}
public class Base : ITest<(int a, int b)>
{
(int a, int b) ITest<(int a, int b)>.M() { return (1, 2); } // explicit implementation
public virtual (int notA, int notB) M() { return (1, 2); }
}
"
Dim csComp = CreateCSharpCompilation(csSource,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime))
csComp.VerifyDiagnostics()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Class Derived1
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
Class Derived2
Inherits Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>, references:={csComp.EmitToImageReference()})
comp.AssertTheseDiagnostics(<errors>
BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'.
Implements ITest(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1")
Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString())
Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2")
Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString())
Dim m = comp.GetTypeByMetadataName("Base").GetMembers("ITest<(System.Int32a,System.Int32b)>.M").Single()
Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(1, mImplementations.Length)
Assert.Equal("Function ITest(Of (System.Int32, System.Int32)).M() As (System.Int32, System.Int32)", mImplementations(0).ToTestDisplayString())
Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M")))
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_03()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ITest(Of T)
Function M() As T
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
Class Derived1
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
Class Derived2
Inherits Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
compilation.AssertTheseDiagnostics(<errors>
BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'.
Implements ITest(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'.
Implements ITest(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_04()
Dim compilation1 = CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Interface ITest(Of T)
Function M() As T
End Interface
Public Class Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>)
compilation1.AssertTheseDiagnostics(<errors>
BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'.
Implements ITest(Of (a As Integer, b As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim compilation2 = CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Class Derived1
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
Class Derived2
Inherits Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>, references:={compilation1.ToMetadataReference()})
compilation2.AssertTheseDiagnostics(<errors>
BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'.
Implements ITest(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_05()
Dim csSource = "
public interface ITest<T>
{
T M();
}
public class Base : ITest<(int a, int b)>
{
public virtual (int a, int b) M() { return (1, 2); }
}
"
Dim csComp = CreateCSharpCompilation(csSource,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime))
csComp.VerifyDiagnostics()
Dim comp = CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Class Derived1
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
End Class
Class Derived2
Inherits Base
Implements ITest(Of (a As Integer, b As Integer))
End Class
]]></file>
</compilation>, references:={csComp.EmitToImageReference()})
comp.AssertTheseDiagnostics(<errors>
BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'.
Implements ITest(Of (notA As Integer, notB As Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1")
Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString())
Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2")
Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString())
Dim m = comp.GetTypeByMetadataName("Base").GetMember("M")
Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations
Assert.Equal(0, mImplementations.Length)
Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M")))
Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M")))
End Sub
<Fact()>
<WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")>
Public Sub ReImplementationAndInference()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ITest(Of T)
Function M() As T
End Interface
Class Base
Implements ITest(Of (a As Integer, b As Integer))
Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M
Return (1, 2)
End Function
End Class
Class Derived
Inherits Base
Implements ITest(Of (notA As Integer, notB As Integer))
Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M
Return (3, 4)
End Function
End Class
Class C
Shared Sub Main()
Dim b As Base = New Derived()
Dim x = Test(b) ' tuple names from Base, implementation from Derived
System.Console.WriteLine(x.a)
End Sub
Shared Function Test(Of T)(t1 As ITest(Of T)) As T
Return t1.M()
End Function
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics()
CompileAndVerify(comp, expectedOutput:="3")
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0)
Assert.Equal("x", x.Identifier.ToString())
Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type
Assert.Equal("(a As System.Int32, b As System.Int32)", xSymbol.ToTestDisplayString())
End Sub
<Fact()>
<WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")>
Public Sub TupleTypeWithTooFewElements()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Shared Sub M(x As Integer, y As (), z As (a As Integer))
End Sub
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC30182: Type expected.
Shared Sub M(x As Integer, y As (), z As (a As Integer))
~
BC37259: Tuple must contain at least two elements.
Shared Sub M(x As Integer, y As (), z As (a As Integer))
~
BC37259: Tuple must contain at least two elements.
Shared Sub M(x As Integer, y As (), z As (a As Integer))
~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim y = nodes.OfType(Of TupleTypeSyntax)().ElementAt(0)
Assert.Equal("()", y.ToString())
Dim yType = model.GetTypeInfo(y)
Assert.Equal("(?, ?)", yType.Type.ToTestDisplayString())
Dim z = nodes.OfType(Of TupleTypeSyntax)().ElementAt(1)
Assert.Equal("(a As Integer)", z.ToString())
Dim zType = model.GetTypeInfo(z)
Assert.Equal("(a As System.Int32, ?)", zType.Type.ToTestDisplayString())
End Sub
<Fact()>
<WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")>
Public Sub TupleExpressionWithTooFewElements()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Dim x = (Alice:=1)
End Class
]]></file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC37259: Tuple must contain at least two elements.
Dim x = (Alice:=1)
~
</errors>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes()
Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(Alice:=1)", tuple.ToString())
Dim tupleType = model.GetTypeInfo(tuple)
Assert.Equal("(Alice As System.Int32, ?)", tupleType.Type.ToTestDisplayString())
End Sub
<Fact>
Public Sub GetWellKnownTypeWithAmbiguities()
Const versionTemplate = "<Assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")>"
Const corlib_vb = "
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Structure IntPtr
End Structure
Public Structure Int32
End Structure
Public Class [String]
End Class
Public Class Attribute
End Class
End Namespace
Namespace System.Reflection
Public Class AssemblyVersionAttribute
Inherits Attribute
Public Sub New(version As String)
End Sub
End Class
End Namespace
"
Const valuetuple_vb As String = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim corlibWithoutVT = CreateEmptyCompilation({String.Format(versionTemplate, "1") + corlib_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib")
corlibWithoutVT.AssertTheseDiagnostics()
Dim corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference()
Dim corlibWithVT = CreateEmptyCompilation({String.Format(versionTemplate, "2") + corlib_vb + valuetuple_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib")
corlibWithVT.AssertTheseDiagnostics()
Dim corlibWithVTRef = corlibWithVT.EmitToImageReference()
Dim libWithVT = CreateEmptyCompilation(valuetuple_vb, references:={corlibWithoutVTRef}, options:=TestOptions.DebugDll)
libWithVT.VerifyDiagnostics()
Dim libWithVTRef = libWithVT.EmitToImageReference()
Dim comp = VisualBasicCompilation.Create("test", references:={libWithVTRef, corlibWithVTRef})
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).IsErrorType())
Dim comp2 = comp.WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True))
Dim tuple2 = comp2.GetWellKnownType(WellKnownType.System_ValueTuple_T2)
Assert.False(tuple2.IsErrorType())
Assert.Equal(libWithVTRef.Display, tuple2.ContainingAssembly.MetadataName.ToString())
Dim comp3 = VisualBasicCompilation.Create("test", references:={corlibWithVTRef, libWithVTRef}). ' order reversed
WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True))
Dim tuple3 = comp3.GetWellKnownType(WellKnownType.System_ValueTuple_T2)
Assert.False(tuple3.IsErrorType())
Assert.Equal(libWithVTRef.Display, tuple3.ContainingAssembly.MetadataName.ToString())
End Sub
<Fact>
Public Sub CheckedConversions()
Dim source =
<compilation>
<file>
Imports System
Class C
Shared Function F(t As (Integer, Integer)) As (Long, Byte)
Return CType(t, (Long, Byte))
End Function
Shared Sub Main()
Try
Dim t = F((-1, -1))
Console.WriteLine(t)
Catch e As OverflowException
Console.WriteLine("overflow")
End Try
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(
source,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False),
references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(-1, 255)]]>)
verifier.VerifyIL("C.F", <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0008: conv.i8
IL_0009: ldloc.0
IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_000f: conv.u1
IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)"
IL_0015: ret
}
]]>)
verifier = CompileAndVerify(
source,
options:=TestOptions.ReleaseExe.WithOverflowChecks(True),
references:=s_valueTupleRefs, expectedOutput:=<![CDATA[overflow]]>)
verifier.VerifyIL("C.F", <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0008: conv.i8
IL_0009: ldloc.0
IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_000f: conv.ovf.u1
IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)"
IL_0015: ret
}
]]>)
End Sub
<Fact>
<WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")>
Public Sub TypelessTupleWithNoImplicitConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
option strict on
Imports System
Module C
Sub M()
Dim e As Integer? = 5
Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'.
Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion
~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind)
End Sub
<Fact>
<WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")>
Public Sub TypelessTupleWithNoImplicitConversion2()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
option strict on
Imports System
Module C
Sub M()
Dim e As Integer? = 5
Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(e As Integer?, Object)' cannot be converted to '(Integer, String, Integer)'.
Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion
~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind)
End Sub
<Fact>
<WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")>
Public Sub TypedTupleWithNoImplicitConversion()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
option strict on
Imports System
Module C
Sub M()
Dim e As Integer? = 5
Dim x as (Integer, String, Integer) = (e, "") ' No conversion
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(<errors>
BC30311: Value of type '(e As Integer?, String)' cannot be converted to '(Integer, String, Integer)'.
Dim x as (Integer, String, Integer) = (e, "") ' No conversion
~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(e, """")", node.ToString())
Assert.Equal("(e As System.Nullable(Of System.Int32), System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString())
Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
Public Sub MoreGenericTieBreaker_01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim a As A(Of A(Of Integer)) = Nothing
M1(a) ' ok, selects M1(Of T)(A(Of A(Of T)) a)
Dim b = New ValueTuple(Of ValueTuple(Of Integer, Integer), Integer)()
M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a)
End Sub
Public Sub M1(Of T)(a As A(Of T))
Console.Write(1)
End Sub
Public Sub M1(Of T)(a As A(Of A(Of T)))
Console.Write(2)
End Sub
Public Sub M2(Of T)(a As ValueTuple(Of T, Integer))
Console.Write(3)
End Sub
Public Sub M2(Of T)(a As ValueTuple(Of ValueTuple(Of T, Integer), Integer))
Console.Write(4)
End Sub
End Module
Public Class A(Of T)
End Class
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
24
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
Public Sub MoreGenericTieBreaker_01b()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim b = ((0, 0), 0)
M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a)
End Sub
Public Sub M2(Of T)(a As (T, Integer))
Console.Write(3)
End Sub
Public Sub M2(Of T)(a As ((T, Integer), Integer))
Console.Write(4)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
4
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a1()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
' Dim b = (1, 2, 3, 4, 5, 6, 7, 8)
Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8))
M1(b)
M2(b)
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a2()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
' Dim b = (1, 2, 3, 4, 5, 6, 7, 8)
Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8))
M1(b)
M2(b)
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a3()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing
M1(b)
M2(b)
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)))
Console.Write(3)
End Sub
End Module
Interface I(Of in T)
End Interface
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a4()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing
M1(b)
M2(b)
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)))
Console.Write(3)
End Sub
End Module
Interface I(Of out T)
End Interface
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a5()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
M1((1, 2, 3, 4, 5, 6, 7, 8))
M2((1, 2, 3, 4, 5, 6, 7, 8))
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a6()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
M2((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8))
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), ValueTuple(Of Func(Of T8))))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest))
Console.Write(3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
2
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02a7()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8))
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest))
Console.Write(1)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs)
comp.AssertTheseDiagnostics(
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8))
~~
</expected>
)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
<WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")>
Public Sub MoreGenericTieBreaker_02b()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports int = System.Int32
Module Module1
Public Sub Main()
Dim b = (1, 2, 3, 4, 5, 6, 7, 8)
M1(b)
M2(b)
End Sub
Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(1)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))
Console.Write(2)
End Sub
Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))
Console.Write(3)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
12
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
Public Sub MoreGenericTieBreaker_03()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, (10, 10), (11, 11))
M1(b) ' ok, should select M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V))
End Sub
Sub M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V))
Console.Write(3)
End Sub
Sub M1(Of T, U, V)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U, (V, Integer)))
Console.Write(4)
End Sub
End Module
</file>
</compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[
3
]]>)
End Sub
<Fact>
<WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")>
Public Sub MoreGenericTieBreaker_04()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, (20, 20))
M1(b) ' error: ambiguous
End Sub
Sub M1(Of T, U)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer)))
Console.Write(3)
End Sub
Sub M1(Of T, U)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U))
Console.Write(4)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "M1").WithArguments("M1", "
'Public Sub M1(Of (Integer, Integer), Integer)(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific.
'Public Sub M1(Of Integer, (Integer, Integer))(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific.").WithLocation(7, 9)
)
End Sub
<Fact>
<WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")>
Public Sub TypelessTupleInArrayInitializer()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module Module1
Private mTupleArray As (X As Integer, P As System.Func(Of Byte(), Integer))() = {
(X:=0, P:=Nothing), (X:=0, P:=AddressOf MyFunction)
}
Sub Main()
System.Console.Write(mTupleArray(1).P(Nothing))
End Sub
Public Function MyFunction(ArgBytes As Byte()) As Integer
Return 1
End Function
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertNoDiagnostics()
CompileAndVerify(comp, expectedOutput:="1")
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString())
Dim tupleSymbol = model.GetTypeInfo(node)
Assert.Null(tupleSymbol.Type)
Assert.Equal("(X As System.Int32, P As System.Func(Of System.Byte(), System.Int32))",
tupleSymbol.ConvertedType.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")>
Public Sub TypelessTupleInArrayInitializerWithInferenceFailure()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module Module1
Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) }
Sub Main()
System.Console.Write(mTupleArray(1).P(Nothing))
End Sub
Public Function MyFunction(ArgBytes As Byte()) As Integer
Return 1
End Function
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors>
BC30491: Expression does not produce a value.
Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0)
Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString())
Dim tupleSymbol = model.GetTypeInfo(node)
Assert.Null(tupleSymbol.Type)
Assert.Equal("System.Object", tupleSymbol.ConvertedType.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")>
Public Sub TypelessTupleInArrayInitializerWithInferenceSuccess()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim y As MyDelegate = AddressOf MyFunction
Dim mTupleArray = { (X:=0, P:=y), (X:=0, P:=AddressOf MyFunction) }
System.Console.Write(mTupleArray(1).P(Nothing))
End Sub
Delegate Function MyDelegate(ArgBytes As Byte()) As Integer
Public Function MyFunction(ArgBytes As Byte()) As Integer
Return 1
End Function
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
comp.AssertNoDiagnostics()
CompileAndVerify(comp, expectedOutput:="1")
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1)
Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString())
Dim tupleSymbol = model.GetTypeInfo(node)
Assert.Null(tupleSymbol.Type)
Assert.Equal("(X As System.Int32, P As Module1.MyDelegate)", tupleSymbol.ConvertedType.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")>
Public Sub InferenceWithTuple()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Public Interface IAct(Of T)
Function Act(Of TReturn)(fn As Func(Of T, TReturn)) As IResult(Of TReturn)
End Interface
Public Interface IResult(Of TReturn)
End Interface
Module Module1
Sub M(impl As IAct(Of (Integer, Integer)))
Dim case3 = impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y)
End Sub
End Module
</file>
</compilation>, additionalRefs:=s_valueTupleRefs)
comp.AssertTheseDiagnostics()
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim actSyntax = nodes.OfType(Of InvocationExpressionSyntax)().Single()
Assert.Equal("impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y)", actSyntax.ToString())
Dim actSymbol = DirectCast(model.GetSymbolInfo(actSyntax).Symbol, IMethodSymbol)
Assert.Equal("IResult(Of System.Int32)", actSymbol.ReturnType.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")>
Public Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType()
Dim vtLib = CreateEmptyCompilation(s_trivial2uple, references:={MscorlibRef}, assemblyName:="vt")
Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class ClassA
Implements IEnumerable(Of (alice As Integer, bob As Integer))
Function GetGenericEnumerator() As IEnumerator(Of (alice As Integer, bob As Integer)) Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator
Return Nothing
End Function
Function GetEnumerator() As IEnumerator Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator
Return Nothing
End Function
End Class
</file>
</compilation>, additionalRefs:={vtLib.EmitToImageReference()})
libComp.VerifyDiagnostics()
Dim source As Xml.Linq.XElement =
<compilation>
<file name="a.vb">
Class ClassB
Sub M()
Dim x = New ClassA()
x.ToString()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt
comp.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp, successfulDecoding:=False)
Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference()}) ' missing reference to vt
compWithMetadataReference.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithMetadataReference, successfulDecoding:=True)
Dim fakeVtLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt")
Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt
compWithFakeVt.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithFakeVt, successfulDecoding:=False)
Dim source2 As Xml.Linq.XElement =
<compilation>
<file name="a.vb">
Class ClassB
Sub M()
Dim x = New ClassA().GetGenericEnumerator()
For Each i In New ClassA()
System.Console.Write(i.alice)
Next
End Sub
End Class
</file>
</compilation>
Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt
comp2.AssertTheseDiagnostics(<errors>
BC30652: Reference required to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'ValueTuple(Of ,)'. Add one to your project.
Dim x = New ClassA().GetGenericEnumerator()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2, successfulDecoding:=False)
Dim comp2WithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt
comp2WithFakeVt.AssertTheseDiagnostics(<errors>
BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'vt.dll' failed.
Dim x = New ClassA().GetGenericEnumerator()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2WithFakeVt, successfulDecoding:=False)
End Sub
Private Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compilation As Compilation, successfulDecoding As Boolean)
Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol)
Dim iEnumerable = classA.Interfaces()(0)
If successfulDecoding Then
Assert.Equal("System.Collections.Generic.IEnumerable(Of (alice As System.Int32, bob As System.Int32))",
iEnumerable.ToTestDisplayString())
Dim tuple = iEnumerable.TypeArguments()(0)
Assert.Equal("(alice As System.Int32, bob As System.Int32)", tuple.ToTestDisplayString())
Assert.True(tuple.IsTupleType)
Assert.True(tuple.TupleUnderlyingType.IsErrorType())
Else
Assert.Equal("System.Collections.Generic.IEnumerable(Of System.ValueTuple(Of System.Int32, System.Int32)[missing])",
iEnumerable.ToTestDisplayString())
Dim tuple = iEnumerable.TypeArguments()(0)
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)[missing]", tuple.ToTestDisplayString())
Assert.False(tuple.IsTupleType)
End If
End Sub
<Fact>
<WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")>
Public Sub FailedDecodingOfTupleNamesWhenMissingContainerType()
Dim containerLib = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class Container(Of T)
Public Class Contained(Of U)
End Class
End Class
</file>
</compilation>)
containerLib.VerifyDiagnostics()
Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class ClassA
Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer)))
Function GetGenericEnumerator() As IEnumerator(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))) _
Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator
Return Nothing
End Function
Function GetEnumerator() As IEnumerator Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator
Return Nothing
End Function
End Class
</file>
</compilation>, additionalRefs:={containerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef})
libComp.VerifyDiagnostics()
Dim source As Xml.Linq.XElement =
<compilation>
<file name="a.vb">
Class ClassB
Sub M()
Dim x = New ClassA()
x.ToString()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source,
additionalRefs:={libComp.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container
comp.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(comp, decodingSuccessful:=False)
Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container
compWithMetadataReference.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithMetadataReference, decodingSuccessful:=True)
Dim fakeContainerLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt")
Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeContainerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' reference to fake container
compWithFakeVt.AssertNoDiagnostics()
FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithFakeVt, decodingSuccessful:=False)
End Sub
Private Sub FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compilation As Compilation, decodingSuccessful As Boolean)
Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol)
Dim iEnumerable = classA.Interfaces()(0)
Dim tuple = DirectCast(iEnumerable.TypeArguments()(0), NamedTypeSymbol).TypeArguments()(0)
If decodingSuccessful Then
Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of (alice As System.Int32, bob As System.Int32))[missing].Contained(Of (charlie As System.Int32, dylan As System.Int32))[missing])", iEnumerable.ToTestDisplayString())
Assert.Equal("(charlie As System.Int32, dylan As System.Int32)", tuple.ToTestDisplayString())
Assert.True(tuple.IsTupleType)
Assert.False(tuple.TupleUnderlyingType.IsErrorType())
Else
Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of System.ValueTuple(Of System.Int32, System.Int32))[missing].Contained(Of System.ValueTuple(Of System.Int32, System.Int32))[missing])", iEnumerable.ToTestDisplayString())
Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", tuple.ToTestDisplayString())
Assert.False(tuple.IsTupleType)
End If
End Sub
<Theory>
<InlineData(True)>
<InlineData(False)>
<WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")>
Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_IndirectInterfaces(ByVal useImageReferences As Boolean)
Dim getReference As Func(Of Compilation, MetadataReference) = Function(c) If(useImageReferences, c.EmitToImageReference(), c.ToMetadataReference())
Dim valueTuple_source = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}""
End Function
End Structure
End Namespace
"
Dim valueTuple_comp = CreateCompilationWithMscorlib40(valueTuple_source)
Dim tupleElementNamesAttribute_comp = CreateCompilationWithMscorlib40(s_tupleattributes)
tupleElementNamesAttribute_comp.AssertNoDiagnostics()
Dim lib1_source = "
Imports System.Threading.Tasks
Public Interface I2(Of T, TResult)
Function ExecuteAsync(parameter As T) As Task(Of TResult)
End Interface
Public Interface I1(Of T)
Inherits I2(Of T, (a As Object, b As Object))
End Interface
"
Dim lib1_comp = CreateCompilationWithMscorlib40(lib1_source, references:={getReference(valueTuple_comp), getReference(tupleElementNamesAttribute_comp)})
lib1_comp.AssertNoDiagnostics()
Dim lib2_source = "
Public interface I0
Inherits I1(Of string)
End Interface
"
Dim lib2_comp = CreateCompilationWithMscorlib40(lib2_source, references:={getReference(lib1_comp), getReference(valueTuple_comp)}) ' Missing TupleElementNamesAttribute
lib2_comp.AssertNoDiagnostics()
lib2_comp.AssertTheseEmitDiagnostics()
Dim imc1 = CType(lib2_comp.GlobalNamespace.GetMember("I0"), TypeSymbol)
AssertEx.SetEqual({"I1(Of System.String)"}, imc1.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString()))
AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc1.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString()))
Dim client_source = "
Public Class C
Public Sub M(imc As I0)
imc.ExecuteAsync("""")
End Sub
End Class
"
Dim client_comp = CreateCompilationWithMscorlib40(client_source, references:={getReference(lib1_comp), getReference(lib2_comp), getReference(valueTuple_comp)})
client_comp.AssertNoDiagnostics()
Dim imc2 = CType(client_comp.GlobalNamespace.GetMember("I0"), TypeSymbol)
AssertEx.SetEqual({"I1(Of System.String)"}, imc2.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString()))
AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc2.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString()))
End Sub
<Fact, WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")>
Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_BaseAndDirectInterface()
Dim source = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}""
End Function
End Structure
End Namespace
Namespace System.Runtime.CompilerServices
Public Class TupleElementNamesAttribute
Inherits Attribute
Public Sub New() ' Note: bad signature
End Sub
End Class
End Namespace
Public Interface I(Of T)
End Interface
Public Class Base(Of T)
End Class
Public Class C1
Implements I(Of (a As Object, b As Object))
End Class
Public Class C2
Inherits Base(Of (a As Object, b As Object))
End Class
"
Dim comp = CreateCompilationWithMscorlib40(source)
comp.AssertTheseEmitDiagnostics(<errors><![CDATA[
BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
Implements I(Of (a As Object, b As Object))
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
Inherits Base(Of (a As Object, b As Object))
~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Theory>
<InlineData(True)>
<InlineData(False)>
<WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")>
Public Sub MissingTypeArgumentInBase_ValueTuple(useImageReference As Boolean)
Dim lib_vb = "
Public Class ClassWithTwoTypeParameters(Of T1, T2)
End Class
Public Class SelfReferencingClassWithTuple
Inherits ClassWithTwoTypeParameters(Of SelfReferencingClassWithTuple, (A As String, B As Integer))
Sub New()
System.Console.Write(""ran"")
End Sub
End Class
"
Dim library = CreateCompilationWithMscorlib40(lib_vb, references:=s_valueTupleRefs)
library.VerifyDiagnostics()
Dim libraryRef = If(useImageReference, library.EmitToImageReference(), library.ToMetadataReference())
Dim source_vb = "
Public Class TriggerStackOverflowException
Public Shared Sub Method()
Dim x = New SelfReferencingClassWithTuple()
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib40(source_vb, references:={libraryRef})
comp.VerifyEmitDiagnostics()
Dim executable_vb = "
Public Class C
Public Shared Sub Main()
TriggerStackOverflowException.Method()
End Sub
End Class
"
Dim executableComp = CreateCompilationWithMscorlib40(executable_vb,
references:={comp.EmitToImageReference(), libraryRef, SystemRuntimeFacadeRef, ValueTupleRef},
options:=TestOptions.DebugExe)
CompileAndVerify(executableComp, expectedOutput:="ran")
End Sub
<Fact>
<WorkItem(41699, "https://github.com/dotnet/roslyn/issues/41699")>
Public Sub MissingBaseType_TupleTypeArgumentWithNames()
Dim sourceA =
"Public Class A(Of T)
End Class"
Dim comp = CreateCompilation(sourceA, assemblyName:="A")
Dim refA = comp.EmitToImageReference()
Dim sourceB =
"Public Class B
Inherits A(Of (X As Object, Y As B))
End Class"
comp = CreateCompilation(sourceB, references:={refA})
Dim refB = comp.EmitToImageReference()
Dim sourceC =
"Module Program
Sub Main()
Dim b = New B()
b.ToString()
End Sub
End Module"
comp = CreateCompilation(sourceC, references:={refB})
comp.AssertTheseDiagnostics(
"BC30456: 'ToString' is not a member of 'B'.
b.ToString()
~~~~~~~~~~
BC30652: Reference required to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A(Of )'. Add one to your project.
b.ToString()
~~~~~~~~~~")
End Sub
<Fact>
<WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")>
<WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")>
Public Sub CustomFields_01()
Dim source0 = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Shared F1 As Integer = 123
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
End Sub
Public Overrides Function ToString() As String
Return F1.ToString()
End Function
End Structure
End Namespace
"
Dim source1 = "
class Program
public Shared Sub Main()
System.Console.WriteLine((1,2).ToString())
End Sub
End Class
"
Dim source2 = "
class Program
public Shared Sub Main()
System.Console.WriteLine(System.ValueTuple(Of Integer, Integer).F1)
End Sub
End Class
"
Dim verifyField = Sub(comp As VisualBasicCompilation)
Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1")
Assert.Null(field.TupleUnderlyingField)
Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single()
Assert.Same(field, toEmit)
End Sub
Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="123")
verifyField(comp1)
Dim comp1Ref = {comp1.ToMetadataReference()}
Dim comp1ImageRef = {comp1.EmitToImageReference()}
Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp4, expectedOutput:="123")
Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp5, expectedOutput:="123")
verifyField(comp5)
Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef)
CompileAndVerify(comp6, expectedOutput:="123")
verifyField(comp6)
Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp7, expectedOutput:="123")
verifyField(comp7)
End Sub
<Fact>
<WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")>
<WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")>
Public Sub CustomFields_02()
Dim source0 = "
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Dim F1 As Integer
Public Dim Item1 As T1
Public Dim Item2 As T2
Public Sub New(item1 As T1, item2 As T2)
me.Item1 = item1
me.Item2 = item2
me.F1 = 123
End Sub
Public Overrides Function ToString() As String
Return F1.ToString()
End Function
End Structure
End Namespace
"
Dim source1 = "
class Program
public Shared Sub Main()
System.Console.WriteLine((1,2).ToString())
End Sub
End Class
"
Dim source2 = "
class Program
public Shared Sub Main()
System.Console.WriteLine((1,2).F1)
End Sub
End Class
"
Dim verifyField = Sub(comp As VisualBasicCompilation)
Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1")
Assert.Null(field.TupleUnderlyingField)
Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single()
Assert.Same(field, toEmit)
End Sub
Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="123")
verifyField(comp1)
Dim comp1Ref = {comp1.ToMetadataReference()}
Dim comp1ImageRef = {comp1.EmitToImageReference()}
Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp4, expectedOutput:="123")
Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp5, expectedOutput:="123")
verifyField(comp5)
Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef)
CompileAndVerify(comp6, expectedOutput:="123")
verifyField(comp6)
Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp7, expectedOutput:="123")
verifyField(comp7)
End Sub
<Fact>
<WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")>
<WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")>
Public Sub CustomFields_03()
Dim source0 = "
namespace System
public structure ValueTuple
public shared readonly F1 As Integer = 4
public Shared Function CombineHashCodes(h1 As Integer, h2 As Integer) As Integer
return F1 + h1 + h2
End Function
End Structure
End Namespace
"
Dim source1 = "
class Program
shared sub Main()
System.Console.WriteLine(System.ValueTuple.CombineHashCodes(2, 3))
End Sub
End Class
"
Dim source2 = "
class Program
public shared Sub Main()
System.Console.WriteLine(System.ValueTuple.F1 + 2 + 3)
End Sub
End Class
"
Dim verifyField = Sub(comp As VisualBasicCompilation)
Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1")
Assert.Null(field.TupleUnderlyingField)
Dim toEmit = field.ContainingType.GetFieldsToEmit().Single()
Assert.Same(field, toEmit)
End Sub
Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="9")
verifyField(comp1)
Dim comp1Ref = {comp1.ToMetadataReference()}
Dim comp1ImageRef = {comp1.EmitToImageReference()}
Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp4, expectedOutput:="9")
Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp5, expectedOutput:="9")
verifyField(comp5)
Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef)
CompileAndVerify(comp6, expectedOutput:="9")
verifyField(comp6)
Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp7, expectedOutput:="9")
verifyField(comp7)
End Sub
<Fact>
<WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")>
<WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")>
Public Sub CustomFields_04()
Dim source0 = "
namespace System
public structure ValueTuple
public F1 as Integer
public Function CombineHashCodes(h1 as Integer, h2 as Integer) as Integer
return F1 + h1 + h2
End Function
End Structure
End Namespace
"
Dim source1 = "
class Program
shared sub Main()
Dim tuple as System.ValueTuple = Nothing
tuple.F1 = 4
System.Console.WriteLine(tuple.CombineHashCodes(2, 3))
End Sub
End Class
"
Dim source2 = "
class Program
public shared Sub Main()
Dim tuple as System.ValueTuple = Nothing
tuple.F1 = 4
System.Console.WriteLine(tuple.F1 + 2 + 3)
End Sub
End Class
"
Dim verifyField = Sub(comp As VisualBasicCompilation)
Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1")
Assert.Null(field.TupleUnderlyingField)
Dim toEmit = field.ContainingType.GetFieldsToEmit().Single()
Assert.Same(field, toEmit)
End Sub
Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="9")
verifyField(comp1)
Dim comp1Ref = {comp1.ToMetadataReference()}
Dim comp1ImageRef = {comp1.EmitToImageReference()}
Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe)
CompileAndVerify(comp4, expectedOutput:="9")
Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp5, expectedOutput:="9")
verifyField(comp5)
Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef)
CompileAndVerify(comp6, expectedOutput:="9")
verifyField(comp6)
Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref)
CompileAndVerify(comp7, expectedOutput:="9")
verifyField(comp7)
End Sub
<Fact>
<WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")>
Public Sub TupleUnderlyingType_FromCSharp()
Dim source =
"#pragma warning disable 169
class Program
{
static System.ValueTuple F0;
static (int, int) F1;
static (int A, int B) F2;
static (object, object, object, object, object, object, object, object) F3;
static (object, object B, object, object D, object, object F, object, object H) F4;
}"
Dim comp = CreateCSharpCompilation(source, referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.Standard))
comp.VerifyDiagnostics()
Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single()
VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "()")
VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)")
VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)")
VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)")
VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)")
End Sub
<Fact>
<WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")>
Public Sub TupleUnderlyingType_FromVisualBasic()
Dim source =
"Class Program
Private F0 As System.ValueTuple
Private F1 As (Integer, Integer)
Private F2 As (A As Integer, B As Integer)
Private F3 As (Object, Object, Object, Object, Object, Object, Object, Object)
Private F4 As (Object, B As Object, Object, D As Object, Object, F As Object, Object, H As Object)
End Class"
Dim comp = CreateCompilation(source)
comp.AssertNoDiagnostics()
Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single()
VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "System.ValueTuple")
VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)")
VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)")
VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)")
VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)")
End Sub
Private Enum TupleUnderlyingTypeValue
[Nothing]
Distinct
Same
End Enum
Private Shared Sub VerifyTypeFromCSharp(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String)
VerifyDisplay(type, expectedCSharp, expectedVisualBasic)
VerifyPublicType(type, expectedValue)
VerifyPublicType(type.OriginalDefinition, TupleUnderlyingTypeValue.Nothing)
End Sub
Private Shared Sub VerifyTypeFromVisualBasic(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String)
VerifyDisplay(type, expectedCSharp, expectedVisualBasic)
VerifyInternalType(type, expectedValue)
VerifyPublicType(type, expectedValue)
type = type.OriginalDefinition
VerifyInternalType(type, expectedValue)
VerifyPublicType(type, expectedValue)
End Sub
Private Shared Sub VerifyDisplay(type As INamedTypeSymbol, expectedCSharp As String, expectedVisualBasic As String)
Assert.Equal(expectedCSharp, CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat))
Assert.Equal(expectedVisualBasic, VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat))
End Sub
Private Shared Sub VerifyInternalType(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue)
Dim underlyingType = type.TupleUnderlyingType
Select Case expectedValue
Case TupleUnderlyingTypeValue.Nothing
Assert.Null(underlyingType)
Case TupleUnderlyingTypeValue.Distinct
Assert.NotEqual(type, underlyingType)
Assert.False(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions))
Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything))
VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing)
Case Else
Throw ExceptionUtilities.UnexpectedValue(expectedValue)
End Select
End Sub
Private Shared Sub VerifyPublicType(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue)
Dim underlyingType = type.TupleUnderlyingType
Select Case expectedValue
Case TupleUnderlyingTypeValue.Nothing
Assert.Null(underlyingType)
Case TupleUnderlyingTypeValue.Distinct
Assert.NotEqual(type, underlyingType)
Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.Default))
Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.ConsiderEverything))
VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing)
Case Else
Throw ExceptionUtilities.UnexpectedValue(expectedValue)
End Select
End Sub
<Fact>
<WorkItem(27322, "https://github.com/dotnet/roslyn/issues/27322")>
Public Sub Issue27322()
Dim source0 = "
Imports System
Imports System.Collections.Generic
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim tupleA = (1, 3)
Dim tupleB = (1, ""123"".Length)
Dim ok1 As Expression(Of Func(Of Integer)) = Function() tupleA.Item1
Dim ok2 As Expression(Of Func(Of Integer)) = Function() tupleA.GetHashCode()
Dim ok3 As Expression(Of Func(Of Tuple(Of Integer, Integer))) = Function() tupleA.ToTuple()
Dim ok4 As Expression(Of Func(Of Boolean)) = Function() Equals(tupleA, tupleB)
Dim ok5 As Expression(Of Func(Of Integer)) = Function() Comparer(Of (Integer, Integer)).Default.Compare(tupleA, tupleB)
ok1.Compile()()
ok2.Compile()()
ok3.Compile()()
ok4.Compile()()
ok5.Compile()()
Dim err1 As Expression(Of Func(Of Boolean)) = Function() tupleA.Equals(tupleB)
Dim err2 As Expression(Of Func(Of Integer)) = Function() tupleA.CompareTo(tupleB)
err1.Compile()()
err2.Compile()()
System.Console.WriteLine(""Done"")
End Sub
End Module
"
Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="Done")
End Sub
<Fact>
<WorkItem(24517, "https://github.com/dotnet/roslyn/issues/24517")>
Public Sub Issue24517()
Dim source0 = "
Imports System
Imports System.Collections.Generic
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim e1 As Expression(Of Func(Of ValueTuple(Of Integer, Integer))) = Function() new ValueTuple(Of Integer, Integer)(1, 2)
Dim e2 As Expression(Of Func(Of KeyValuePair(Of Integer, Integer))) = Function() new KeyValuePair(Of Integer, Integer)(1, 2)
e1.Compile()()
e2.Compile()()
System.Console.WriteLine(""Done"")
End Sub
End Module
"
Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe)
CompileAndVerify(comp1, expectedOutput:="Done")
End Sub
End Class
End Namespace
|
davkean/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
|
Visual Basic
|
apache-2.0
| 925,955
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTests
Public Class VisualBasicConflicts
<Fact(Skip:="798375, 799977")>
<WorkItem(798375)>
<WorkItem(773543)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Class D
Public x As Integer = 1
End Class
Dim a As Action(Of Integer) = Sub([|$$x|] As Integer)
Dim {|Conflict:y|} = New D()
Console.{|Conflict:WriteLine|}({|Conflict:x|})
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact(Skip:="798375")>
<WorkItem(798375)>
<WorkItem(773534)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Structure y
Public x As Integer
End Structure
Class C
Class D
Public x As Integer = 1
Dim w As Action(Of y) = Sub([|$$x|] As y)
Dim {|Conflict:y|} = New D()
Console.WriteLine(y.x)
Console.WriteLine({|Conflict:x|}.{|Conflict:x|})
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(857937)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub HandleInvocationExpressions()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub [|$$Main|](args As String())
Dim x As New Dictionary(Of Integer, Dictionary(Of Integer, Integer))
Console.WriteLine(x(1)(3))
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="x")
End Using
End Sub
<Fact>
<WorkItem(773435)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Delegate Sub Foo(x As Integer)
Public Sub FooMeth(x As Integer)
End Sub
Public Sub void()
Dim {|Conflict:x|} As Foo = New Foo(AddressOf FooMeth)
Dim [|$$z|] As Integer = 1
Dim y As Integer = {|Conflict:z|}
x({|Conflict:z|})
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(782020)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports A = N.{|Conflict:X|}
Namespace N
Class {|Conflict:X|}
End Class
End Namespace
Namespace N
Class {|Conflict:$$Y|}
End Class
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="X")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub OverloadResolutionConflictResolve_1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Runtime.CompilerServices
Module C
<Extension()>
Public Sub Ex(x As String)
End Sub
Sub Outer(x As Action(Of String), y As Object)
Console.WriteLine(1)
End Sub
Sub Outer(x As Action(Of Integer), y As Integer)
Console.WriteLine(2)
End Sub
Sub Inner(x As Action(Of String), y As String)
End Sub
Sub Inner(x As Action(Of String), y As Integer)
End Sub
Sub Inner(x As Action(Of Integer), y As Integer)
End Sub
Sub Main()
{|conflict1:Outer|}(Sub(y) {|conflict2:Inner|}(Sub(x) x.Ex(), y), 0)
Outer(Sub(y As Integer)
Inner(CType(Sub(x)
Console.WriteLine(x)
x.Ex()
End Sub, Action(Of String)), y)
End Sub, 0)
End Sub
End Module
Module E
' Rename Ex To Foo
<Extension()>
Public Sub [|$$Ex|](x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("conflict2", "Outer(Sub(y As String) Inner(Sub(x) x.Ex(), y), 0)", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict1", "Outer(Sub(y As String) Inner(Sub(x) x.Ex(), y), 0)", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub OverloadResolutionConflictResolve_2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Runtime.CompilerServices
Module C
<Extension()>
Public Sub Ex(x As String)
End Sub
Sub Outer(x As Action(Of String), y As Object)
Console.WriteLine(1)
End Sub
Sub Outer(x As Action(Of Integer), y As Integer)
Console.WriteLine(2)
End Sub
Sub Inner(x As Action(Of String), y As String)
End Sub
Sub Inner(x As Action(Of String), y As Integer)
End Sub
Sub Inner(x As Action(Of Integer), y As Integer)
End Sub
Sub Main()
{|conflict2:Outer|}(Sub(y)
{|conflict1:Inner|}(Sub(x)
Console.WriteLine(x)
x.Ex()
End Sub, y)
End Sub, 0)
End Sub
End Module
Module E
' Rename Ex To Foo
<Extension()>
Public Sub [|$$Ex|](x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="z")
Dim outputResult = <Code>Outer(Sub(y As String)</Code>.Value + vbCrLf +
<Code> Inner(Sub(x)</Code>.Value + vbCrLf +
<Code> Console.WriteLine(x)</Code>.Value + vbCrLf +
<Code> x.Ex()</Code>.Value + vbCrLf +
<Code> End Sub, y)</Code>.Value + vbCrLf +
<Code> End Sub, 0)</Code>.Value
result.AssertLabeledSpansAre("conflict2", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict1", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub OverloadResolutionConflictResolve_3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Runtime.CompilerServices
Module C
<Extension()>
Public Sub Ex(x As String)
End Sub
Sub Outer(x As Action(Of String), y As Object)
Console.WriteLine(1)
End Sub
Sub Outer(x As Action(Of Integer), y As Integer)
Console.WriteLine(2)
End Sub
Sub Inner(x As Action(Of String), y As String)
End Sub
Sub Inner(x As Action(Of String), y As Integer)
End Sub
Sub Inner(x As Action(Of Integer), y As Integer)
End Sub
Sub Main()
{|conflict1:Outer|}(Sub(y)
{|conflict2:Inner|}(Sub(x)
Console.WriteLine(x)
Dim z = 5
z.{|conflict0:Ex|}()
x.Ex()
End Sub, y)
End Sub, 0)
End Sub
End Module
Module E
' Rename Ex To Foo
<Extension()>
Public Sub [|$$Ex|](x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="foo")
Dim outputResult = <Code>Outer(Sub(y As String)</Code>.Value + vbCrLf +
<Code> Inner(Sub(x)</Code>.Value + vbCrLf +
<Code> Console.WriteLine(x)</Code>.Value + vbCrLf +
<Code> Dim z = 5</Code>.Value + vbCrLf +
<Code> z.foo()</Code>.Value + vbCrLf +
<Code> x.Ex()</Code>.Value + vbCrLf +
<Code> End Sub, y)</Code>.Value + vbCrLf +
<Code> End Sub, 0)</Code>.Value
result.AssertLabeledSpansAre("conflict0", outputResult, type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict2", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict1", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub OverloadResolutionConflictResolve_4()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Runtime.CompilerServices
Module C
<Extension()>
Public Sub Ex(x As String)
End Sub
Sub Outer(x As Action(Of String), y As Object)
Console.WriteLine(1)
End Sub
Sub Outer(x As Action(Of Integer), y As Integer)
Console.WriteLine(2)
End Sub
Sub Inner(x As Action(Of String), y As String)
End Sub
Sub Inner(x As Action(Of String), y As Integer)
End Sub
Sub Inner(x As Action(Of Integer), y As Integer)
End Sub
Sub Main()
{|conflict1:Outer|}(Sub(y)
{|conflict2:Inner|}(Sub(x)
Console.WriteLine(x)
Dim z = 5
z.{|conflict0:blah|}()
x.Ex()
End Sub, y)
End Sub, 0)
End Sub
End Module
Module E
' Rename blah To Ex
<Extension()>
Public Sub [|$$blah|](x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Ex")
Dim outputResult = <Code>Outer(Sub(y)</Code>.Value + vbCrLf +
<Code> Inner(Sub(x As String)</Code>.Value + vbCrLf +
<Code> Console.WriteLine(x)</Code>.Value + vbCrLf +
<Code> Dim z = 5</Code>.Value + vbCrLf +
<Code> z.Ex()</Code>.Value + vbCrLf +
<Code> x.Ex()</Code>.Value + vbCrLf +
<Code> End Sub, y)</Code>.Value + vbCrLf +
<Code> End Sub, 0)</Code>.Value
result.AssertLabeledSpansAre("conflict0", outputResult, type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict2", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict1", outputResult, type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameStatementWithResolvingAndUnresolvingConflictInSameStatement_VB()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim z As Object
Sub Main(args As String())
Dim sx = Function([|$$x|] As Integer)
{|resolve:z|} = Nothing
If (True) Then
Dim z As Boolean = {|conflict1:foo|}({|conflict2:x|})
End If
Return True
End Function
End Sub
Public Function foo(bar As Integer) As Boolean
Return True
End Function
Public Function foo(bar As Object) As Boolean
Return bar
End Function
End Module
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("conflict2", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("conflict1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("resolve", "Program.z = Nothing", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(729401)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IntroduceWhitespaceTriviaToInvocationIfCallKeywordIsIntroduced()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb">
Module M
Public Sub [|$$Foo|](Of T)(ByVal x As T) ' Rename Foo to Bar
End Sub
End Module
Class C
Public Sub Bar(ByVal x As String)
End Sub
Class M
Public Shared Bar As Action(Of String) = Sub(ByVal x As String)
End Sub
End Class
Public Sub Test()
{|stmt1:Foo|}("1")
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Call Global.M.Bar(""1"")", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(728646)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class CC
Public Shared Sub [|$$Foo|](Of T)(x As T)
End Sub
Public Shared Sub Bar(x As Integer)
End Sub
Public Sub Baz()
End Sub
End Class
Class D
Public Sub Baz()
CC.{|stmt1:Foo|}(1)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "CC.Bar(Of Integer)(1)", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(725934), WorkItem(639136)>
<Fact()>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_Me()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Public Sub TestMethod()
Dim x = 1
Dim y = {|stmt1:F|}(x)
End Sub
Public Function F(Of T)(x As T) As Integer
Return 1
End Function
Public Function [|$$B|](x As Integer) As Integer
Return 1
End Function
End Class
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "Dim y = F(Of Integer)(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Shared Sub F(Of T)(x As Func(Of Integer, T))
End Sub
Shared Sub [|$$B|](x As Func(Of Integer, Integer))
End Sub
Shared Sub main()
{|stmt1:F|}(Function(a) a)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F(Of Integer)(Function(a) a)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_Nested()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub [|$$Foo|](Of T)(ByVal x As T)
End Sub
Public Shared Sub Bar(ByVal x As Integer)
End Sub
Class D
Sub Bar(Of T)(ByVal x As T)
End Sub
Sub Bar(ByVal x As Integer)
End Sub
Sub Test()
{|stmt1:Foo|}(1)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar(Of Integer)(1)", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_ReferenceType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Public Sub Foo(Of T)(ByVal x As T)
End Sub
Public Sub [|$$Bar|](ByVal x As String)
End Sub
Public Sub Test()
Dim x = "1"
{|stmt1:Foo|}(x)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of String)(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136), WorkItem(569103), WorkItem(755801)>
<Fact(Skip:="755801"), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_Cref()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of T)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_DifferentScope1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Public Sub [|$$Foo|](Of T)(ByVal x As T) ' Rename Foo to Bar
End Sub
Public Sub Bar(ByVal x As Integer)
End Sub
End Module
Class C
Public Sub Bar(ByVal x As Integer)
End Sub
Class M
Public Shared Bar As Action(Of Integer) = Sub(ByVal x As Integer)
End Sub
End Class
Public Sub Test()
{|stmt1:Foo|}(1)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Call Global.M.Bar(Of Integer)(1)", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_ConstructedTypeArgumentGenericContainer()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C(Of S)
Public Shared Sub Foo(Of T)(ByVal x As T)
End Sub
Public Shared Sub [|$$Bar|](ByVal x As C(Of Integer))
End Sub
Public Sub Test()
Dim x As C(Of Integer) = New C(Of Integer)()
{|stmt1:Foo|}(x)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of C(Of Integer))(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_ConstructedTypeArgumentNonGenericContainer()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub Foo(Of T)(ByVal x As T)
End Sub
Public Shared Sub [|$$Bar|](ByVal x As D(Of Integer))
End Sub
Public Sub Test()
Dim x As D(Of Integer) = New D(Of Integer)()
{|stmt1:Foo|}(x)
End Sub
End Class
Class D(Of S)
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of D(Of Integer))(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_ObjectType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub Foo(Of T)(ByVal x As T)
End Sub
Public Shared Sub [|$$Bar|](ByVal x As Object)
End Sub
Public Sub Test()
Dim x = DirectCast(1, Object)
{|stmt1:Foo|}(x)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of Object)(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_SameTypeParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub Foo(Of T)(ByVal x As T)
End Sub
Public Shared Sub [|$$Bar|](Of T)(ByVal x As T())
End Sub
Public Sub Test()
Dim x As Integer() = New Integer() {1, 2, 3}
{|stmt1:Foo|}(x)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of Integer())(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_MultiDArrayTypeParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub Foo(Of T)(ByVal x As T)
End Sub
Public Shared Sub [|$$Bar|](Of T)(ByVal x As T(,))
End Sub
Public Sub Test()
Dim x As Integer(,) = New Integer(,) {{1, 2}, {2, 3}, {3, 4}}
{|stmt1:Foo|}(x)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of Integer(,))(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_UsedAsArgument()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Function Foo(Of T)(ByVal x As T) As Integer
Return 1
End Function
Public Function [|$$Bar|](ByVal x As Integer) As Integer
Return 1
End Function
Public Sub Method(ByVal x As Integer)
End Sub
Public Sub Test()
Method({|stmt1:Foo|}(1))
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Method(Foo(Of Integer)(1))", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_UsedInConstructorInitialization()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub New(ByVal x As Integer)
End Sub
Public Function Foo(Of T)(ByVal x As T) As Integer
Return 1
End Function
Public Function [|$$Bar|](ByVal x As Integer) As Integer
Return 1
End Function
Public Sub Method()
Dim x As New C({|stmt1:Foo|}(1))
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Dim x As New C(Foo(Of Integer)(1))", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_CalledOnObject()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Function Foo(Of T)(ByVal x As T) As Integer
Return 1
End Function
Public Function [|$$Bar|](ByVal x As Integer) As Integer
Return 1
End Function
Public Sub Method()
Dim x As New C()
x.{|stmt1:Foo|}(1)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "x.Foo(Of Integer)(1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_UsedInGenericDelegate()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Delegate Function FooDel(Of T)(ByVal x As T) As Integer
Public Function Foo(Of T)(ByVal x As T) As Integer
Return 1
End Function
Public Function [|$$Bar|](ByVal x As String) As Integer
Return 1
End Function
Public Sub Method()
Dim x = New FooDel(Of String)(AddressOf {|stmt1:Foo|})
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Dim x = New FooDel(Of String)(AddressOf Foo(Of String))", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_UsedInNonGenericDelegate()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Delegate Function FooDel(ByVal x As String) As Integer
Public Function Foo(Of T)(ByVal x As T) As Integer
Return 1
End Function
Public Function [|$$Bar|](ByVal x As String) As Integer
Return 1
End Function
Public Sub Method()
Dim x = New FooDel(AddressOf {|stmt1:Foo|})
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Dim x = New FooDel(AddressOf Foo(Of String))", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_MultipleTypeParameters()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Shared Sub Foo(Of T, S)(ByVal x As T, ByVal y As S)
End Sub
Public Shared Sub [|$$Bar|](Of T, S)(ByVal x As T(), ByVal y As S)
End Sub
Public Sub Test()
Dim x = New Integer() {1, 2}
{|stmt1:Foo|}(x, New C())
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo(Of Integer(), C)(x, New C())", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WorkItem(730781)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionWithTypeInference_ConflictInDerived()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Sub Foo(Of T)(ByRef x As T)
End Sub
Public Sub Foo(ByRef x As String)
End Sub
End Class
Class D
Inherits C
Public Sub [|$$Bar|](ByRef x As Integer)
End Sub
Public Sub Test()
Dim x As String
{|stmt1:Foo|}(x)
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "MyBase.Foo(x)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class FooClass
Private foo As Integer
Sub Blah([|$$bar|] As Integer)
{|stmt2:foo|} = {|stmt1:bar|}
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "Me.foo = foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Me.foo = foo", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class FooClass
Private [if] As Integer
Sub Blah({|Escape:$$bar|} As Integer)
{|stmt2:[if]|} = {|stmt1:bar|}
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "[if]", RelatedLocationType.NoConflict)
' we don't unescape [if] in Me.[if] because the user gave it to us escaped.
result.AssertLabeledSpecialSpansAre("stmt1", "Me.[if] = [if]", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("stmt2", "Me.[if] = [if]", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class FooClass
Private {|escape:$$bar|} As Integer
Sub Blah([if] As Integer)
{|stmt1:bar|} = [if]
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="if")
result.AssertLabeledSpecialSpansAre("escape", "[if]", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt1", "Me.if = [if]", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithSharedField()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class FooClass
Shared foo As Integer
Sub Blah([|$$bar|] As Integer)
{|stmt2:foo|} = {|stmt1:bar|}
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "FooClass.foo = foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "FooClass.foo = foo", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldInModule()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Private foo As Integer
Sub Blah([|$$bar|] As Integer)
{|stmt2:foo|} = {|stmt1:bar|}
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "FooModule.foo = foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "FooModule.foo = foo", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class X
Protected Class [|$$A|]
End Class
End Class
Class Y
Inherits X
Protected Class C
Inherits {|Resolve:A|}
End Class
Class B
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class X
Protected Class A
End Class
End Class
Class Y
Inherits X
Protected Class C
Inherits {|Resolve:A|}
End Class
Class [|$$B|]
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub PreserveTypeCharactersForKeywordsAsIdentifiers()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Class C
Sub New
Dim x$ = Me.{|stmt1:$$Foo|}.ToLower
End Sub
Function {|TypeSuffix:Foo$|}
Return "ABC"
End Function
End Class
</Document>
</Project>
</Workspace>, renameTo:="Class")
result.AssertLabeledSpansAre("stmt1", "Class", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("TypeSuffix", "Class$", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(529695)>
<WorkItem(543016)>
<Fact(Skip:="529695"), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameDoesNotBreakQuery()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim col1 As New Col
Dim query = From i In col1 Select i
End Sub
End Module
Public Class Col
Function {|escaped:$$[Select]|}(ByVal sel As Func(Of Integer, Integer)) As IEnumerable(Of Integer)
Return Nothing
End Function
End Class
</Document>
</Project>
</Workspace>, renameTo:="FooSelect")
result.AssertLabeledSpansAre("escaped", "[FooSelect]", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact(Skip:="566460")>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(566460)>
<WorkItem(542349)>
Public Sub ProperlyEscapeNewKeywordWithTypeCharacters()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Class C
Sub New
Dim x$ = Me.{|stmt1:$$Foo$|}.ToLower
End Sub
Function {|Unescaped:Foo$|}
Return "ABC"
End Function
End Class
</Document>
</Project>
</Workspace>, renameTo:="New")
result.AssertLabeledSpansAre("Unescaped", "New$", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt1", "Dim x$ = Me.[New].ToLower", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub AvoidDoubleEscapeAttempt()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module [|$$Program|]
Sub Main()
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="[true]")
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ReplaceAliasWithNestedGenericType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports C = A(Of Integer).B
Class A(Of T)
Class B
End Class
End Class
Module M
Sub Main
Dim x As {|stmt1:C|}
End Sub
Class [|D$$|]
End Class
End Module
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "Dim x As A(Of Integer).B", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(540440)>
Public Sub RenamingFunctionWithFunctionVariableFromFunction()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Function [|$$X|]() As Integer
{|stmt1:X|} = 1
End Function
End Module
</Document>
</Project>
</Workspace>, renameTo:="BarBaz")
result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(540440)>
Public Sub RenamingFunctionWithFunctionVariableFromFunctionVariable()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Function [|X|]() As Integer
{|stmt1:$$X|} = 1
End Function
End Module
</Document>
</Project>
</Workspace>, renameTo:="BarBaz")
result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact(Skip:="566542")>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542999)>
<WorkItem(566542)>
Public Sub ResolveConflictingTypeIncludedThroughModule1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Inherits N.{|Replacement:A|}
End Class
Namespace N
Module X
Class A
End Class
End Module
Module Y
Class [|$$B|]
End Class
End Module
End Namespace
]]></Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Replacement", "N.X.A", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact(Skip:="566542")>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543068)>
<WorkItem(566542)>
Public Sub ResolveConflictingTypeIncludedThroughModule2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Inherits {|Replacement:N.{|Resolved:A|}|}
End Class
Namespace N
Module X
Class [|$$A|]
End Class
End Module
Module Y
Class B
End Class
End Module
End Namespace
]]></Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("Replacement", "N.X.B")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543068)>
Public Sub ResolveConflictingTypeImportedFromMultipleTypes()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports X
Imports Y
Module Program
Sub Main
{|stmt1:Foo|} = 1
End Sub
End Module
Class X
Public Shared [|$$Foo|]
End Class
Class Y
Public Shared Bar
End Class
]]></Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "X.Bar = 1", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542936)>
Public Sub ConflictWithImplicitlyDeclaredLocal()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Explicit Off
Module Program
Function [|$$Foo|]
{|Conflict:Bar|} = 1
End Function
End Module
]]></Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542886)>
Public Sub RenameForRangeVariableUsedInLambda()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Module Program
Sub Main(args As String())
For {|stmt1:$$i|} = 1 To 20
Dim q As Action = Sub()
Console.WriteLine({|stmt1:i|})
End Sub
Next
End Sub
End Module
]]></Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(543021)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ShouldNotCascadeToExplicitlyImplementedInterfaceMethodOfDifferentName()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Interface MyInterface
Sub Bar()
End Interface
Public Structure MyStructure
Implements MyInterface
Private Sub [|$$I_Bar|]() Implements MyInterface.Bar
End Sub
End Structure
</Document>
</Project>
</Workspace>, renameTo:="Baz")
End Using
End Sub
<Fact>
<WorkItem(543021)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ShouldNotCascadeToImplementingMethodOfDifferentName()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Interface MyInterface
Sub [|$$Bar|]()
End Interface
Public Structure MyStructure
Implements MyInterface
Private Sub I_Bar() Implements MyInterface.[|Bar|]
End Sub
End Structure
</Document>
</Project>
</Workspace>, renameTo:="Baz")
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<{|Special:Something|}()>
Public class foo
End class
Public Class [|$$SomethingAttribute|]
Inherits Attribute
End Class]]></Document>
</Project>
</Workspace>, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeFromUsage()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<{|Special:Something|}()>
Public class foo
End class
Public Class {|Special:$$SomethingAttribute|}
Inherits Attribute
End Class]]></Document>
</Project>
</Workspace>, renameTo:="Special")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(543488)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionCallAfterElse()
' This is a simple scenario but it has a somewhat strange tree in VB. The
' BeginTerminator of the ElseBlockSyntax is missing, and just so happens to land at
' the same location as the NewMethod invocation that follows the Else.
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Module Program
Sub Main(ByRef args As String())
If (True)
Else {|stmt1:NewMethod|}() :
End If
End Sub
Private Sub [|$$NewMethod|]()
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="NewMethod1")
result.AssertLabeledSpansAre("stmt1", "NewMethod1", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(11004, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameImplicitlyDeclaredLocal()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Option Explicit Off
Module Program
Sub Main(args As String())
{|stmt1:$$foo|} = 23
{|stmt2:foo|} = 42
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="barbaz")
result.AssertLabeledSpansAre("stmt1", "barbaz", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "barbaz", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(11004, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFieldToConflictWithImplicitlyDeclaredLocal()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Option Explicit Off
Module Program
Dim [|$$bar|] As Object
Sub Main(args As String())
{|stmt1_2:foo|} = {|stmt1:bar|}
{|stmt2:foo|} = 42
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "foo", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt1_2", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(543420)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameParameterOfEvent()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Class Test
Public Event Percent(ByVal [|$$p|] As Single)
Public Shared Sub Main()
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="barbaz")
End Using
End Sub
<WorkItem(543587)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameLocalInMethodMissingParameterList()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Imports System
Module Program
Sub Main
Dim {|stmt1:$$a|} As Integer
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="barbaz")
result.AssertLabeledSpansAre("stmt1", "barbaz", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(542649)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Class A
End Class
Class B
Dim x As {|Resolve:A|}
Class [|$$C|]
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "Global.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(542322)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyFieldInReDimStatement()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Module Preserve
Sub Main
Dim Bar
ReDim {|stmt1:Foo|}(0)
End Sub
Property [|$$Foo|]
End Module
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "ReDim [Preserve].Bar(0)", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(566542)>
<WorkItem(545604)>
<Fact(Skip:="566542"), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeNameInImports()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Imports {|Resolve:X|}
Module M
Class X
End Class
End Module
Module N
Class [|$$Y|] ' Rename Y to X
End Class
End Module
</Document>
</Project>
</Workspace>, renameTo:="X")
result.AssertLabeledSpansAre("Resolve", "M.X", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNewOverload()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Imports System
Module Program
Sub Main()
{|ResolvedNonReference:Foo|}(Sub(x) x.{|Resolve:Old|}())
End Sub
Sub Foo(x As Action(Of I))
End Sub
Sub Foo(x As Action(Of C))
End Sub
End Module
Interface I
Sub {|Escape:$$Old|}()
End Interface
Class C
Sub [New]()
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="New")
result.AssertLabeledSpecialSpansAre("Escape", "[New]", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve", "Foo(Sub(x) x.New())", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ResolvedNonReference", "Foo(Sub(x) x.New())", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeRequiringReducedNameToResolveConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Public Class [|$$YAttribute|]
Inherits System.Attribute
End Class
Public Class ZAttributeAttribute
Inherits System.Attribute
End Class
<{|resolve:YAttribute|}>
Class Class1
End Class
Class Class2
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="ZAttribute")
result.AssertLabeledSpecialSpansAre("resolve", "Z", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameEvent()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Imports System
Namespace N
Public Interface I
Event [|$$X|] As EventHandler ' Rename X to Y
End Interface
End Namespace
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document FilePath="Test.cs">
using System;
using N;
class C : I
{
event EventHandler I.[|X|]
{
add { }
remove { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="Y")
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInterfaceImplementation()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Imports System
Interface I
Sub Foo(Optional x As Integer = 0)
End Interface
Class C
Implements I
Shared Sub Main()
DirectCast(New C(), I).Foo()
End Sub
Private Sub [|$$I_Foo|](Optional x As Integer = 0) Implements I.Foo
Console.WriteLine("test")
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeConflictWithNamespace()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
Namespace X
Class [|$$A|] ' Rename A to B
Inherits Attribute
End Class
Namespace N.BAttribute
<{|Resolve:A|}>
Delegate Sub F()
End Namespace
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameREMToUnicodeREM()
Dim text = ChrW(82) & ChrW(69) & ChrW(77)
Dim compareText = "[" & text & "]"
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb">
Module {|Resolve:$$[REM]|}
End Module
</Document>
</Project>
</Workspace>, renameTo:=text)
result.AssertLabeledSpecialSpansAre("Resolve", compareText, RelatedLocationType.NoConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameImports()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports [|$$S|] = System.Collections
Imports System
Namespace X
<A>
Class A
Inherits {|Resolve1:Attribute|}
End Class
End Namespace
Module M
Dim a As {|Resolve2:S|}.ArrayList
End Module
]]>
</Document>
</Project>
</Workspace>, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve1", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve2", "Attribute", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(578105)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug578105_VBRenamingPartialMethodDifferentCasing()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Class Foo
Partial Private Sub [|Foo|]()
End Sub
Private Sub [|$$foo|]()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="Baz")
End Using
End Sub
<WorkItem(588142)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug588142_SimplifyAttributeUsageCanAlwaysEscapeInVB()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<{|escaped:A|}>
Class [|$$AAttribute|] ' Rename A to RemAttribute
Inherits Attribute
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="RemAttribute")
result.AssertLabeledSpansAre("escaped", "[Rem]", RelatedLocationType.NoConflict)
End Using
End Sub
<WorkItem(588038)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug588142_RenameAttributeToAttribute()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<{|unreduced:Foo|}>
Class [|$$FooAttribute|] ' Rename Foo to Attribute
Inherits {|resolved:Attribute|}
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="Attribute")
result.AssertLabeledSpansAre("unreduced", "Attribute", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(576573)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
Namespace X
Class B
Inherits Attribute
End Class
Namespace N.[|$$Y|] ' Rename Y to BAttribute
<{|resolved:B|}>
Delegate Sub F()
End Namespace
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="BAttribute")
result.AssertLabeledSpansAre("resolved", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(603368)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug603368_ConflictAttributeWithNamespaceCaseInsensitve()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
Namespace X
Class B
Inherits Attribute
End Class
Namespace N.[|$$Y|] ' Rename Y to BAttribute
<{|resolved:B|}>
Delegate Sub F()
End Namespace
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="BATTRIBUTE")
result.AssertLabeledSpansAre("resolved", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(603367)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug603367_ConflictAttributeWithNamespaceCaseInsensitve2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<{|resolved:Foo|}>
Module M
Class FooAttribute
Inherits Attribute
End Class
End Module
Class [|$$X|] ' Rename X to FOOATTRIBUTE
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="FOOATTRIBUTE")
result.AssertLabeledSpansAre("resolved", "M.Foo", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(603276)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug603276_ConflictAttributeWithNamespaceCaseInsensitve3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Imports System
<[|Foo|]>
Class [|$$Foo|] ' Rename Foo to ATTRIBUTE
Inherits {|resolved:Attribute|}
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="ATTRIBUTE")
result.AssertLabeledSpansAre("resolved", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(529712)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug529712_ConflictNamespaceWithModuleName_1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="Test.vb"><![CDATA[
Module Program
Sub Main()
N.{|resolved:Foo|}()
End Sub
End Module
Namespace N
Namespace [|$$Y|] ' Rename Y to Foo
End Namespace
Module X
Sub Foo()
End Sub
End Module
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "N.X.Foo()", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(529837)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug529837_ResolveConflictByOmittingModuleName()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Namespace X
Public Module Y
Public Class C
End Class
End Module
End Namespace
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true">
<ProjectReference>Project1</ProjectReference>
<Document>
Namespace X
Namespace Y
Class [|$$D|]
Inherits {|resolved:C|}
End Class
End Namespace
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("resolved", "X.C", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(529989)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug529989_RenameCSharpIdentifierToInvalidVBIdentifier()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" AssemblyName="Project1" CommonReferences="true">
<Document>
public class {|invalid:$$ProgramCS|}
{
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true">
<ProjectReference>Project1</ProjectReference>
<Document>
Module ProgramVB
Sub Main(args As String())
Dim d As {|invalid:ProgramCS|}
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="B\u0061r")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("invalid", "B\u0061r", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameModuleBetweenAssembly()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<ProjectReference>Project2</ProjectReference>
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim {|Stmt1:$$Bar|} = Sub(x) Console.Write(x)
Call {|Resolve:Foo|}()
{|Stmt2:Bar|}(1)
End Sub
End Module
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true">
<Document>
Public Module M
Sub Foo()
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Stmt2", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve", "Call M.Foo()", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameModuleClassConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Imports System
Namespace N
Module M
Class C
Shared Sub Foo()
End Sub
End Class
End Module
Class [|$$D|]
Shared Sub Foo()
End Sub
End Class
Module Program
Sub Main()
{|Resolve:C|}.{|Resolve:Foo|}()
{|Stmt1:D|}.Foo()
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "M.C.Foo()", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Stmt1", "C", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameModuleNamespaceNested()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Imports System
Namespace N
Namespace M
Module K
Sub Foo()
End Sub
End Module
Module L
Sub [|$$Bar|]()
End Sub
End Module
End Namespace
End Namespace
Module Program
Sub Main(args As String())
N.M.{|Resolve1:Foo|}()
N.M.{|Resolve2:Bar|}()
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve1", "N.M.K.Foo()", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve2", "N.M.L.Foo()", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameModuleConflictWithInterface()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Imports System
Interface M
Sub foo(ByVal x As Integer)
End Interface
Namespace N
Module [|$$K|]
Sub foo(ByVal x As Integer)
End Sub
End Module
Class C
Implements {|Resolve:M|}
Public Sub foo(x As Integer) Implements {|Resolve:M|}.foo
Throw New NotImplementedException()
End Sub
End Class
End Namespace </Document>
</Project>
</Workspace>, renameTo:="M")
result.AssertLabeledSpansAre("Resolve", "Global.M", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(628700)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameModuleConflictWithLocal()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Imports System
Namespace N
Class D
Public x() As Integer = {0, 1}
End Class
Module M
Public x() As Integer = {0, 1}
End Module
Module S
Dim M As New D()
Dim [|$$y|] As Integer
Dim p = From x In M.x Select x
Dim q = From x In {|Resolve:x|} Select x
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("Resolve", "N.M.x", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(633180)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_DetectOverLoadResolutionChangesInEnclosingInvocations()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs">
Imports System
Imports System.Runtime.CompilerServices
Module C
<Extension()>
Public Sub Ex(x As String)
End Sub
Sub Outer(x As Action(Of String), y As Object)
Console.WriteLine(1)
End Sub
Sub Outer(x As Action(Of Integer), y As Integer)
Console.WriteLine(2)
End Sub
Sub Inner(x As Action(Of String), y As String)
End Sub
Sub Inner(x As Action(Of String), y As Integer)
End Sub
Sub Inner(x As Action(Of Integer), y As Integer)
End Sub
Sub Main()
{|resolved:Outer|}(Sub(y) {|resolved:Inner|}(Sub(x) x.Ex(), y), 0)
End Sub
End Module
Module E
' Rename Ex To Foo
<Extension()>
Public Sub [|$$Ex|](x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer(Sub(y As String) Inner(Sub(x) x.Ex(), y), 0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562), WorkItem(569103)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace NN
Class C
''' <see cref="{|resolve1:NN|}.C"/>
Public x As {|resolve2:NN|}.C
End Class
Namespace [|$$KK|]
Class C
End Class
End Namespace
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="NN")
result.AssertLabeledSpansAre("resolve1", "Global.NN.C", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", "Global.NN", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs">
Namespace N
Class C
Public x As {|resolve:N|}.C
End Class
Class [|$$D|]
Class C
Public y As [|D|]
End Class
End Class
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "Global.N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(645152)>
<Fact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub AdjustTriviaForExtensionMethodRewrite()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs">
Imports System.Runtime.CompilerServices
Class C
Sub Bar(tag As Integer)
Me.{|resolve:Foo|}(1).{|resolve:Foo|}(2)
End Sub
End Class
Module E
<Extension>
Public Function [|$$Foo|](x As C, tag As Integer) As C
Return x
End Function
End Module
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "E.Bar(E.Bar(Me,1),2)", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(569103)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports F = N
Namespace N
Interface I
Sub Foo()
End Interface
End Namespace
Class C
Private Class E
Implements {|Resolve:F|}.I
''' <summary>
''' This is a function <see cref="{|Resolve:F|}.I.Foo"/>
''' </summary>
Public Sub Foo() Implements {|Resolve:F|}.I.Foo
End Sub
End Class
Private Class [|$$K|]
End Class
End Class
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb">
<![CDATA[
Public Class A
Public Class B
Public Class C
End Class
''' <summary>
''' <see cref=" {|Resolve:D|}"/>
''' ''' </summary>
Shared Sub [|$$foo|]() ' Rename foo to D
End Sub
End Class
Public Class D
End Class
End Class
]]>
</Document>
</Project>
</Workspace>, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1016652)>
Public Sub VB_ConflictBetweenTypeNamesInTypeConstraintSyntax()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System.Collections.Generic
Public Interface {|unresolved1:$$INamespaceSymbol|}
End Interface
Public Interface {|DeclConflict:ISymbol|}
End Interface
Public Interface IReferenceFinder
End Interface
Friend MustInherit Partial Class AbstractReferenceFinder(Of TSymbol As {|unresolved2:INamespaceSymbol|})
Implements IReferenceFinder
End Class
]]></Document>
</Project>
</Workspace>, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(905, "https://github.com/dotnet/roslyn/issues/905")>
Public Sub RenamingCompilerGeneratedPropertyBackingField_InvokeFromProperty()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C1
Public ReadOnly Property [|X$$|] As String
Sub M()
{|backingfield:_X|} = "test"
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Y")
result.AssertLabeledSpecialSpansAre("backingfield", "_Y", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(905, "https://github.com/dotnet/roslyn/issues/905")>
Public Sub RenamingCompilerGeneratedPropertyBackingField_IntroduceConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C1
Public ReadOnly Property [|X$$|] As String
Sub M()
{|Conflict:_X|} = "test"
End Sub
Dim _Y As String
End Class
</Document>
</Project>
</Workspace>, renameTo:="Y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(905, "https://github.com/dotnet/roslyn/issues/905")>
Public Sub RenamingCompilerGeneratedPropertyBackingField_InvokableFromBackingFieldReference()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C1
Public ReadOnly Property [|X|] As String
Sub M()
{|backingfield:_X$$|} = "test"
End Sub
End Class
</Document>
</Project>
</Workspace>)
AssertTokenRenamable(workspace)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C
Shared Sub F([|$$z|] As Integer)
Dim x = NameOf({|ref:zoo|})
End Sub
Dim zoo As Integer
End Class
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "Dim x = NameOf(C.zoo)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C
Sub F([|$$z|] As Integer)
Dim x = NameOf({|ref:zoo|})
End Sub
Shared zoo As Integer
End Class
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "Dim x = NameOf(C.zoo)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true">
<Document>
Class C
Sub F([|$$z|] As Integer)
Dim x = NameOf({|ref:zoo|})
End Sub
Dim zoo As Integer
End Class
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "Dim x = NameOf(C.zoo)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
Class {|conflict:C|}
End Class
Interface [|$$I|]
End Interface
]]>
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
Class [|$$C|]
End Class
Interface {|conflict:I|}
End Interface
]]>
</Document>
</Project>
</Workspace>, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
Class {|conflict:$$C|}
End Class
Namespace N
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
Class {|conflict:C|}
End Class
Namespace [|$$N|]
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
Namespace [|$$N1|]
End Namespace
Namespace N2
End Namespace
]]>
</Document>
</Project>
</Workspace>, renameTo:="N2")
End Using
End Sub
End Class
End Class
End Namespace
|
paladique/roslyn
|
src/EditorFeatures/Test2/Rename/RenameEngineTests.VisualBasicConflicts.vb
|
Visual Basic
|
apache-2.0
| 104,168
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class TunnelForm
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Me.animationTimer = New System.Windows.Forms.Timer(Me.components)
Me.SuspendLayout()
'
'animationTimer
'
Me.animationTimer.Enabled = True
Me.animationTimer.Interval = 10
'
'TunnelForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.Black
Me.ClientSize = New System.Drawing.Size(632, 453)
Me.DoubleBuffered = True
Me.Font = New System.Drawing.Font("Segoe UI", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Name = "TunnelForm"
Me.Text = "Tunnel"
Me.ResumeLayout(False)
End Sub
Friend WithEvents animationTimer As Timer
End Class
|
kaiaie/DisplayHacks
|
Tunnel/TunnelForm.Designer.vb
|
Visual Basic
|
bsd-3-clause
| 1,885
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports Bytescout.PDF
''' <summary>
''' This example demonstrates how to fill PDF form programmatically.
''' </summary>
Class Program
Shared Sub Main()
' Map of form fields and sample values to set
Dim fieldMap As New Dictionary(Of String, Object)()
fieldMap.Add("f1_01[0]", "John J") ' FirstName And middle initial
fieldMap.Add("f1_02[0]", "Smith") ' LastName
fieldMap.Add("f1_03[0]", "111-111-3333") ' Security number
fieldMap.Add("f1_04[0]", "12 Palm st., Hill Valley") ' Home address
fieldMap.Add("f1_05[0]", "CA 12345") ' City, Town, State And ZIP
fieldMap.Add("c1_1[1]", "True") ' Married
fieldMap.Add("f1_06[0]", "123") ' Total number of allowance
fieldMap.Add("f1_07[0]", "443.44") ' Additional amount
fieldMap.Add("f1_09[0]", "Google, Somewhere in CA") ' Employer's name and address
fieldMap.Add("f1_10[0]", "12-3-2012") ' First date of employment
fieldMap.Add("f1_11[0]", "EMP223344") ' Employer identification number
' Load PDF form
Dim pdfDocument = New Document("W-4.pdf")
pdfDocument.RegistrationName = "demo"
pdfDocument.RegistrationKey = "demo"
' Get first page
Dim page = pdfDocument.Pages(0)
' Get widget by its name and change value
For Each keyValuePair In fieldMap
Dim annotation As Annotation = page.Annotations(keyValuePair.Key)
If TypeOf (annotation) Is CheckBox Then
CType(annotation, CheckBox).Checked = CType(keyValuePair.Value, Boolean)
ElseIf TypeOf (annotation) Is EditBox Then
CType(annotation, EditBox).Text = CType(keyValuePair.Value, String)
End If
Next
' Save modified document
pdfDocument.Save("result.pdf")
' Cleanup
pdfDocument.Dispose()
' Open document in default PDF viewer app
Process.Start("result.pdf")
End Sub
End Class
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Fill form w-4 with pdf sdk/Program.vb
|
Visual Basic
|
apache-2.0
| 2,993
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.EditAndContinue
Friend Class EditAndContinueTestHelper
Public Shared Function CreateTestWorkspace() As TestWorkspace
' create workspace
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { }
</Document>
</Project>
</Workspace>
Return TestWorkspace.Create(test)
End Function
Public Class TestDiagnosticAnalyzerService
Implements IDiagnosticAnalyzerService, IDiagnosticUpdateSource
Private ReadOnly _data As ImmutableArray(Of DiagnosticData)
Public Sub New()
End Sub
Public Sub New(data As ImmutableArray(Of DiagnosticData))
Me._data = data
End Sub
Public ReadOnly Property SupportGetDiagnostics As Boolean Implements IDiagnosticUpdateSource.SupportGetDiagnostics
Get
Return True
End Get
End Property
Public Event DiagnosticsUpdated As EventHandler(Of DiagnosticsUpdatedArgs) Implements IDiagnosticUpdateSource.DiagnosticsUpdated
Public Function GetDiagnostics(workspace As Microsoft.CodeAnalysis.Workspace, projectId As ProjectId, documentId As DocumentId, id As Object, includeSuppressedDiagnostics As Boolean, cancellationToken As CancellationToken) As ImmutableArray(Of DiagnosticData) Implements IDiagnosticUpdateSource.GetDiagnostics
Return If(includeSuppressedDiagnostics, _data, _data.WhereAsArray(Function(d) Not d.IsSuppressed))
End Function
Public Sub Reanalyze(workspace As Microsoft.CodeAnalysis.Workspace, Optional projectIds As IEnumerable(Of ProjectId) = Nothing, Optional documentIds As IEnumerable(Of DocumentId) = Nothing, Optional highPriority As Boolean = False) Implements IDiagnosticAnalyzerService.Reanalyze
End Sub
Public Function GetDiagnosticDescriptors(projectOpt As Project) As ImmutableDictionary(Of String, ImmutableArray(Of DiagnosticDescriptor)) Implements IDiagnosticAnalyzerService.GetDiagnosticDescriptors
Return ImmutableDictionary(Of String, ImmutableArray(Of DiagnosticDescriptor)).Empty
End Function
Public Function GetDiagnosticsForSpanAsync(document As Document, range As TextSpan, Optional includeSuppressedDiagnostics As Boolean = False, Optional diagnosticId As String = Nothing, Optional cancellationToken As CancellationToken = Nothing) As Task(Of IEnumerable(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetDiagnosticsForSpanAsync
Return Task.FromResult(SpecializedCollections.EmptyEnumerable(Of DiagnosticData))
End Function
Public Function TryAppendDiagnosticsForSpanAsync(document As Document, range As TextSpan, diagnostics As List(Of DiagnosticData), Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of Boolean) Implements IDiagnosticAnalyzerService.TryAppendDiagnosticsForSpanAsync
Return Task.FromResult(False)
End Function
Public Function GetSpecificCachedDiagnosticsAsync(workspace As Microsoft.CodeAnalysis.Workspace, id As Object, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetSpecificCachedDiagnosticsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetCachedDiagnosticsAsync(workspace As Microsoft.CodeAnalysis.Workspace, Optional projectId As ProjectId = Nothing, Optional documentId As DocumentId = Nothing, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetCachedDiagnosticsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetSpecificDiagnosticsAsync(solution As Solution, id As Object, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetSpecificDiagnosticsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetDiagnosticsAsync(solution As Solution, Optional projectId As ProjectId = Nothing, Optional documentId As DocumentId = Nothing, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetDiagnosticsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetDiagnosticsForIdsAsync(solution As Solution, Optional projectId As ProjectId = Nothing, Optional documentId As DocumentId = Nothing, Optional diagnosticIds As ImmutableHashSet(Of String) = Nothing, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetDiagnosticsForIdsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetProjectDiagnosticsForIdsAsync(solution As Solution, Optional projectId As ProjectId = Nothing, Optional diagnosticIds As ImmutableHashSet(Of String) = Nothing, Optional includeSuppressedDiagnostics As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As Task(Of ImmutableArray(Of DiagnosticData)) Implements IDiagnosticAnalyzerService.GetProjectDiagnosticsForIdsAsync
Return SpecializedTasks.EmptyImmutableArray(Of DiagnosticData)()
End Function
Public Function GetDiagnosticDescriptors(analyzer As DiagnosticAnalyzer) As ImmutableArray(Of DiagnosticDescriptor) Implements IDiagnosticAnalyzerService.GetDiagnosticDescriptors
Return ImmutableArray(Of DiagnosticDescriptor).Empty
End Function
Public Function IsCompilerDiagnostic(language As String, diagnostic As DiagnosticData) As Boolean Implements IDiagnosticAnalyzerService.IsCompilerDiagnostic
Return False
End Function
Public Function GetCompilerDiagnosticAnalyzer(language As String) As DiagnosticAnalyzer Implements IDiagnosticAnalyzerService.GetCompilerDiagnosticAnalyzer
Return Nothing
End Function
Public Function IsCompilerDiagnosticAnalyzer(language As String, analyzer As DiagnosticAnalyzer) As Boolean Implements IDiagnosticAnalyzerService.IsCompilerDiagnosticAnalyzer
Return False
End Function
Public Function ContainsDiagnostics(workspace As Microsoft.CodeAnalysis.Workspace, projectId As ProjectId) As Boolean Implements IDiagnosticAnalyzerService.ContainsDiagnostics
Throw New NotImplementedException()
End Function
Public Function GetHostAnalyzerReferences() As IEnumerable(Of AnalyzerReference) Implements IDiagnosticAnalyzerService.GetHostAnalyzerReferences
Throw New NotImplementedException()
End Function
End Class
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/VisualStudio/Core/Test/EditAndContinue/EditAndContinueTestHelper.vb
|
Visual Basic
|
apache-2.0
| 8,379
|
' 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.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks
<PartNotDiscoverable>
<Export(GetType(VisualStudioWorkspace))>
<Export(GetType(VisualStudioWorkspaceImpl))>
<Export(GetType(MockVisualStudioWorkspace))>
Friend Class MockVisualStudioWorkspace
Inherits VisualStudioWorkspaceImpl
Private _workspace As TestWorkspace
<ImportingConstructor>
<System.Diagnostics.CodeAnalysis.SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be marked with 'ObsoleteAttribute'", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(exportProvider As ExportProvider)
MyBase.New(exportProvider, exportProvider.GetExportedValue(Of MockServiceProvider))
End Sub
Public Sub SetWorkspace(testWorkspace As TestWorkspace)
_workspace = testWorkspace
SetCurrentSolution(testWorkspace.CurrentSolution)
' HACK: ensure this service is created so it can be used during disposal
Me.Services.GetService(Of IWorkspaceEventListenerService)()
End Sub
Public Overrides Function CanApplyChange(feature As ApplyChangesKind) As Boolean
Return _workspace.CanApplyChange(feature)
End Function
Protected Overrides Sub ApplyDocumentTextChanged(documentId As DocumentId, newText As SourceText)
Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.WithDocumentText(documentId, newText)))
SetCurrentSolution(_workspace.CurrentSolution)
End Sub
Public Overrides Sub CloseDocument(documentId As DocumentId)
_workspace.CloseDocument(documentId)
SetCurrentSolution(_workspace.CurrentSolution)
End Sub
Protected Overrides Sub ApplyDocumentRemoved(documentId As DocumentId)
Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.RemoveDocument(documentId)))
SetCurrentSolution(_workspace.CurrentSolution)
End Sub
Friend Overrides Function OpenInvisibleEditor(documentId As DocumentId) As IInvisibleEditor
Return New MockInvisibleEditor(documentId, _workspace)
End Function
Public Overrides Function TryGoToDefinition(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean
Throw New NotImplementedException()
End Function
Public Overrides Function TryGoToDefinitionAsync(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Task(Of Boolean)
Throw New NotImplementedException()
End Function
Public Overrides Function TryFindAllReferences(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean
Throw New NotImplementedException()
End Function
Public Overrides Sub DisplayReferencedSymbols(solution As Solution, referencedSymbols As IEnumerable(Of ReferencedSymbol))
Throw New NotImplementedException()
End Sub
Friend Overrides Function GetBrowseObject(symbolListItem As SymbolListItem) As Object
Throw New NotImplementedException()
End Function
Public Overrides Sub EnsureEditableDocuments(documents As IEnumerable(Of DocumentId))
' Nothing to do here
End Sub
End Class
Public Class MockInvisibleEditor
Implements IInvisibleEditor
Private ReadOnly _documentId As DocumentId
Private ReadOnly _workspace As TestWorkspace
Private ReadOnly _needsClose As Boolean
Public Sub New(documentId As DocumentId, workspace As TestWorkspace)
Me._documentId = documentId
Me._workspace = workspace
If Not workspace.IsDocumentOpen(documentId) Then
_workspace.OpenDocument(documentId)
_needsClose = True
End If
End Sub
Public ReadOnly Property TextBuffer As Global.Microsoft.VisualStudio.Text.ITextBuffer Implements IInvisibleEditor.TextBuffer
Get
Return Me._workspace.GetTestDocument(Me._documentId).GetTextBuffer()
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
If _needsClose Then
_workspace.CloseDocument(_documentId)
End If
End Sub
End Class
End Namespace
|
sharwell/roslyn
|
src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.vb
|
Visual Basic
|
mit
| 5,372
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class WithKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithInLambdaTest()
VerifyRecommendationsContain(<MethodBody>
Dim x = Sub()
|
End Sub</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithNotAfterExitKeywordTest()
VerifyRecommendationsMissing(<MethodBody>
With
Exit |
Loop</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithNotAfterContinueKeywordTest()
VerifyRecommendationsMissing(<MethodBody>
With
Continue |
Loop</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithNotAfterContinueKeywordOutsideLoopTest()
VerifyRecommendationsMissing(<MethodBody>
Continue |
</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithNotAfterExitKeywordOutsideLoopTest()
VerifyRecommendationsMissing(<MethodBody>
Exit |
</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithNotAfterExitInsideLambdaInsideWithBlockTest()
VerifyRecommendationsMissing(<MethodBody>
While
Dim x = Sub()
Exit |
End Sub
Loop
</MethodBody>, "With")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WithAfterExitInsideWhileLoopInsideLambdaTest()
VerifyRecommendationsMissing(<MethodBody>
Dim x = Sub()
With x
Exit |
Loop
End Sub
</MethodBody>, "With")
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Statements/WithKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,693
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class EventDeclarationHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function GetHighlighterType() As Type
Return GetType(EventDeclarationHighlighter)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Event|]|} Goo() [|Implements|] I1.Goo
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_2() As Task
Await TestAsync(<Text>
Class C
[|Public Event|] Goo() {|Cursor:[|Implements|]|} I1.Goo
End Class</Text>)
End Function
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/EventDeclarationHighlighterTests.vb
|
Visual Basic
|
mit
| 1,182
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports System.Collections.Immutable
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class TypeVariablesExpansionTests
Inherits VisualBasicResultProviderTestBase
<Fact>
Public Sub TypeVariables()
Dim source0 =
"Class A
End Class
Class B
Inherits A
Friend Shared F As Object = 1
End Class"
Dim assembly0 = GetAssembly(source0)
Dim type0 = assembly0.GetType("B")
Dim source1 =
".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
}"
Dim assemblyBytes As ImmutableArray(Of Byte) = Nothing
Dim pdbBytes As ImmutableArray(Of Byte) = Nothing
BasicTestBase.EmitILToArray(source1, appendDefaultHeader:=True, includePdb:=False, assemblyBytes:=assemblyBytes, pdbBytes:=pdbBytes)
Dim assembly1 = ReflectionUtilities.Load(assemblyBytes)
Dim type1 = assembly1.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType({GetType(Integer), type0})
Dim value = CreateDkmClrValue(value:=Nothing, type:=type1, valueFlags:=DkmClrValueFlags.Synthetic)
Dim result = FormatResult("typevars", value)
Verify(result,
EvalResult("Type variables", "", "", Nothing, DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data))
Dim children = GetChildren(result)
Verify(children,
EvalResult("T", "Integer", "Integer", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("U", "B", "B", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data))
End Sub
End Class
End Namespace
|
bbarry/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.vb
|
Visual Basic
|
apache-2.0
| 2,223
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SymbolExtensions
<Extension>
Public Function IsMyNamespace(symbol As ISymbol, compilation As Compilation) As Boolean
If symbol.Kind <> SymbolKind.Namespace OrElse symbol.Name <> "My" Then
Return False
End If
Dim containingNamespace = symbol.ContainingNamespace
Return containingNamespace IsNot Nothing AndAlso
(containingNamespace.IsGlobalNamespace OrElse Object.Equals(containingNamespace, compilation.RootNamespace))
End Function
<Extension>
Public Function IsMyFormsProperty(symbol As ISymbol, compilation As Compilation) As Boolean
If symbol.Kind <> SymbolKind.Property OrElse symbol.Name <> "Forms" Then
Return False
End If
Dim type = DirectCast(symbol, IPropertySymbol).Type
If type Is Nothing OrElse
type.Name <> "MyForms" Then
Return False
End If
Dim containingType = symbol.ContainingType
If containingType Is Nothing OrElse
containingType.ContainingType IsNot Nothing OrElse
containingType.Name <> "MyProject" Then
Return False
End If
Dim containingNamespace = containingType.ContainingNamespace
Return containingNamespace.IsMyNamespace(compilation)
End Function
End Module
End Namespace
|
mmitche/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/SymbolExtensions.vb
|
Visual Basic
|
apache-2.0
| 1,786
|
Public Class frmMoney
Dim generator As New Random
Dim varNumber As Integer = generator.Next(0, 8)
Dim varFirstCoin As Decimal
Dim varSecondCoin As Decimal
Dim varTotal As Decimal
Dim varAnswer As Decimal
Dim varCorrect As Boolean = False
Private Sub frmMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtWelcome.Text = "Hello " + General.Name + " please answer the money questions"
txtCount.Text = General.Answered + 1 & " of " & General.MaxQuestion + 1
GetMoney()
End Sub
Private Sub btnMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMenu.Click
General.ClearResults()
General.MenuAction(Me, frmMenu)
End Sub
Private Sub CheckAns(ByVal sender As Object)
varAnswer = String.Format("{0:C}", sender.Text)
If (varTotal = varAnswer) Then
imgDetails.Visible = True
txtDetails.Visible = True
txtDetails.Text = "Well Done"
imgDetails.Image = My.Resources.accept
If varCorrect = False Then
General.Correct = General.Correct + 1
End If
varCorrect = True
btnNext.Focus()
Else
imgDetails.Visible = True
txtDetails.Visible = True
txtDetails.Text = "Try Again"
imgDetails.Image = My.Resources.delete
End If
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
If General.Answered <> General.MaxQuestion Then
varCorrect = False
imgDetails.Visible = False
txtDetails.Visible = False
GetMoney()
General.Answered = General.Answered + 1
txtCount.Text = General.Answered + 1 & " of " & General.MaxQuestion + 1
Else
General.Topic = "Money"
General.MenuAction(Me, frmAward)
End If
End Sub
Private Sub GetMoney()
Dim temp As Integer = generator.Next(0, 2)
If temp = 0 Then
varFirstCoin = NewMoney(pbMoney)
varSecondCoin = NewMoney(pbMoeny2)
varTotal = varFirstCoin + varSecondCoin
money1.Text = String.Format("{0:C}", varTotal)
money2.Text = String.Format("{0:C}", NewMoney())
Do While money1.Text = money2.Text
money2.Text = String.Format("{0:C}", NewMoney())
Loop
ElseIf temp = 1 Then
varFirstCoin = NewMoney(pbMoney)
varSecondCoin = NewMoney(pbMoeny2)
varTotal = varFirstCoin + varSecondCoin
money1.Text = String.Format("{0:C}", NewMoney)
money2.Text = String.Format("{0:C}", varTotal)
Do While money1.Text = money2.Text
money1.Text = String.Format("{0:C}", NewMoney)
Loop
End If
End Sub
Public Sub NewMoney(ByVal first As Decimal, ByVal coinlbl As ComponentFactory.Krypton.Toolkit.KryptonWrapLabel, ByVal coin As PictureBox)
varNumber = generator.Next(0, 8)
Select Case varNumber
Case 0
first = 0.01
Case 1
first = 0.02
Case 2
first = 0.05
Case 3
first = 0.1
Case 4
first = 0.2
Case 5
first = 0.5
Case 6
first = 1.0
Case 7
first = 2.0
End Select
coinlbl.Text = String.Format("{0:C}", first)
coin.Image = imgMoney.Images(varNumber)
End Sub
Public Function NewMoney(ByVal coin As PictureBox)
Dim first As Decimal
varNumber = generator.Next(0, 8)
Select Case varNumber
Case 0
first = 0.01
Case 1
first = 0.02
Case 2
first = 0.05
Case 3
first = 0.1
Case 4
first = 0.2
Case 5
first = 0.5
Case 6
first = 1.0
Case 7
first = 2.0
End Select
coin.Image = imgMoney.Images(varNumber)
Return first
End Function
Public Function NewMoney()
Dim first As Decimal
varNumber = generator.Next(0, 8)
Select Case varNumber
Case 0
first = 0.01
Case 1
first = 0.02
Case 2
first = 0.05
Case 3
first = 0.1
Case 4
first = 0.2
Case 5
first = 0.5
Case 6
first = 1.0
Case 7
first = 2.0
End Select
Return first
End Function
Private Sub money_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles money1.Click, money2.Click
CheckAns(sender)
End Sub
End Class
|
meamod/Maths123
|
Maths123/frmMoney.vb
|
Visual Basic
|
mit
| 5,067
|
Partial Class RepMovCuentas
'NOTE: The following procedure is required by the telerik Reporting Designer
'It can be modified using the telerik Reporting Designer.
'Do not modify it using the code editor.
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(RepMovCuentas))
Dim ReportParameter1 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim ReportParameter2 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim ReportParameter3 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim ReportParameter4 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim StyleRule1 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule2 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule3 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule4 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Me.SDSRepMovCuentas = New Telerik.Reporting.SqlDataSource()
Me.labelsGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.labelsGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.labelsGroup = New Telerik.Reporting.Group()
Me.cuentaGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.TextBox3 = New Telerik.Reporting.TextBox()
Me.abonoMECaptionTextBox = New Telerik.Reporting.TextBox()
Me.cargoMECaptionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox4 = New Telerik.Reporting.TextBox()
Me.abonoMNCaptionTextBox = New Telerik.Reporting.TextBox()
Me.cargoMNCaptionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox83 = New Telerik.Reporting.TextBox()
Me.glosaCaptionTextBox = New Telerik.Reporting.TextBox()
Me.fechaDocumentoCaptionTextBox = New Telerik.Reporting.TextBox()
Me.rucCaptionTextBox = New Telerik.Reporting.TextBox()
Me.nroChequeCaptionTextBox = New Telerik.Reporting.TextBox()
Me.codigoCaptionTextBox = New Telerik.Reporting.TextBox()
Me.idSubDiarioCaptionTextBox = New Telerik.Reporting.TextBox()
Me.razonSocialCaptionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox10 = New Telerik.Reporting.TextBox()
Me.TextBox9 = New Telerik.Reporting.TextBox()
Me.TextBox8 = New Telerik.Reporting.TextBox()
Me.TextBox7 = New Telerik.Reporting.TextBox()
Me.TextBox6 = New Telerik.Reporting.TextBox()
Me.cuentaDataTextBox = New Telerik.Reporting.TextBox()
Me.cuentaGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.cuentaGroup = New Telerik.Reporting.Group()
Me.reportFooter = New Telerik.Reporting.ReportFooterSection()
Me.pageHeader = New Telerik.Reporting.PageHeaderSection()
Me.TextBox29 = New Telerik.Reporting.TextBox()
Me.TextBox12 = New Telerik.Reporting.TextBox()
Me.TextBox13 = New Telerik.Reporting.TextBox()
Me.TextBox14 = New Telerik.Reporting.TextBox()
Me.TextBox15 = New Telerik.Reporting.TextBox()
Me.TextBox16 = New Telerik.Reporting.TextBox()
Me.TextBox28 = New Telerik.Reporting.TextBox()
Me.TextBox31 = New Telerik.Reporting.TextBox()
Me.TextBox30 = New Telerik.Reporting.TextBox()
Me.titleTextBox = New Telerik.Reporting.TextBox()
Me.TextBox41 = New Telerik.Reporting.TextBox()
Me.pageFooter = New Telerik.Reporting.PageFooterSection()
Me.reportHeader = New Telerik.Reporting.ReportHeaderSection()
Me.detail = New Telerik.Reporting.DetailSection()
Me.TextBox11 = New Telerik.Reporting.TextBox()
Me.abonoMEDataTextBox = New Telerik.Reporting.TextBox()
Me.cargoMEDataTextBox = New Telerik.Reporting.TextBox()
Me.abonoMNDataTextBox = New Telerik.Reporting.TextBox()
Me.cargoMNDataTextBox = New Telerik.Reporting.TextBox()
Me.glosaDataTextBox = New Telerik.Reporting.TextBox()
Me.razonSocialDataTextBox = New Telerik.Reporting.TextBox()
Me.rucDataTextBox = New Telerik.Reporting.TextBox()
Me.nroChequeDataTextBox = New Telerik.Reporting.TextBox()
Me.codigoDataTextBox = New Telerik.Reporting.TextBox()
Me.idSubDiarioDataTextBox = New Telerik.Reporting.TextBox()
Me.fechaDocumentoDataTextBox = New Telerik.Reporting.TextBox()
Me.abonoMESumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.cargoMESumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.abonoMNSumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.cargoMNSumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox2 = New Telerik.Reporting.TextBox()
Me.TextBox5 = New Telerik.Reporting.TextBox()
Me.TextBox17 = New Telerik.Reporting.TextBox()
Me.TextBox20 = New Telerik.Reporting.TextBox()
Me.TextBox21 = New Telerik.Reporting.TextBox()
Me.TextBox22 = New Telerik.Reporting.TextBox()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'SDSRepMovCuentas
'
Me.SDSRepMovCuentas.ConnectionString = "cnx"
Me.SDSRepMovCuentas.Name = "SDSRepMovCuentas"
Me.SDSRepMovCuentas.Parameters.AddRange(New Telerik.Reporting.SqlDataSourceParameter() {New Telerik.Reporting.SqlDataSourceParameter("@Fecha", System.Data.DbType.DateTime, "=Parameters.Fecha.Value"), New Telerik.Reporting.SqlDataSourceParameter("@idProyecto", System.Data.DbType.Int32, "=Parameters.idProyecto.Value"), New Telerik.Reporting.SqlDataSourceParameter("@CuentaInicio", System.Data.DbType.AnsiStringFixedLength, "=Parameters.CuentaInicio.Value"), New Telerik.Reporting.SqlDataSourceParameter("@CuentaFin", System.Data.DbType.AnsiStringFixedLength, "=Parameters.CuentaFin.Value")})
Me.SDSRepMovCuentas.SelectCommand = "dbo.RepMovCuentas"
Me.SDSRepMovCuentas.SelectCommandType = Telerik.Reporting.SqlDataSourceCommandType.StoredProcedure
'
'labelsGroupHeader
'
Me.labelsGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupHeader.Name = "labelsGroupHeader"
Me.labelsGroupHeader.PrintOnEveryPage = True
Me.labelsGroupHeader.Style.Visible = False
'
'labelsGroupFooter
'
Me.labelsGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupFooter.Name = "labelsGroupFooter"
Me.labelsGroupFooter.Style.Visible = False
'
'labelsGroup
'
Me.labelsGroup.GroupFooter = Me.labelsGroupFooter
Me.labelsGroup.GroupHeader = Me.labelsGroupHeader
Me.labelsGroup.Name = "labelsGroup"
'
'cuentaGroupHeader
'
Me.cuentaGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.cuentaGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox3, Me.abonoMECaptionTextBox, Me.cargoMECaptionTextBox, Me.TextBox4, Me.abonoMNCaptionTextBox, Me.cargoMNCaptionTextBox, Me.TextBox83, Me.glosaCaptionTextBox, Me.fechaDocumentoCaptionTextBox, Me.rucCaptionTextBox, Me.nroChequeCaptionTextBox, Me.codigoCaptionTextBox, Me.idSubDiarioCaptionTextBox, Me.razonSocialCaptionTextBox, Me.TextBox10, Me.TextBox9, Me.TextBox8, Me.TextBox7, Me.TextBox6, Me.cuentaDataTextBox})
Me.cuentaGroupHeader.Name = "cuentaGroupHeader"
Me.cuentaGroupHeader.PageBreak = Telerik.Reporting.PageBreak.Before
Me.cuentaGroupHeader.PrintOnEveryPage = True
'
'TextBox3
'
Me.TextBox3.CanGrow = True
Me.TextBox3.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.TextBox3.Style.Font.Name = "Arial"
Me.TextBox3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox3.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox3.StyleName = "Caption"
Me.TextBox3.Value = "AREA"
'
'abonoMECaptionTextBox
'
Me.abonoMECaptionTextBox.CanGrow = True
Me.abonoMECaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMECaptionTextBox.Name = "abonoMECaptionTextBox"
Me.abonoMECaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMECaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.abonoMECaptionTextBox.Style.Font.Name = "Arial"
Me.abonoMECaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMECaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.abonoMECaptionTextBox.StyleName = "Caption"
Me.abonoMECaptionTextBox.Value = "ABONO"
'
'cargoMECaptionTextBox
'
Me.cargoMECaptionTextBox.CanGrow = True
Me.cargoMECaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMECaptionTextBox.Name = "cargoMECaptionTextBox"
Me.cargoMECaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMECaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.cargoMECaptionTextBox.Style.Font.Name = "Arial"
Me.cargoMECaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMECaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cargoMECaptionTextBox.StyleName = "Caption"
Me.cargoMECaptionTextBox.Value = "CARGO"
'
'TextBox4
'
Me.TextBox4.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Name = "TextBox4"
Me.TextBox4.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(4.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.None
Me.TextBox4.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.TextBox4.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Outset
Me.TextBox4.Style.Font.Bold = True
Me.TextBox4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox4.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.TextBox4.Value = "IMPORTE EN DOLARES"
'
'abonoMNCaptionTextBox
'
Me.abonoMNCaptionTextBox.CanGrow = True
Me.abonoMNCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNCaptionTextBox.Name = "abonoMNCaptionTextBox"
Me.abonoMNCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.abonoMNCaptionTextBox.Style.Font.Name = "Arial"
Me.abonoMNCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMNCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.abonoMNCaptionTextBox.StyleName = "Caption"
Me.abonoMNCaptionTextBox.Value = "ABONO"
'
'cargoMNCaptionTextBox
'
Me.cargoMNCaptionTextBox.CanGrow = True
Me.cargoMNCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNCaptionTextBox.Name = "cargoMNCaptionTextBox"
Me.cargoMNCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.cargoMNCaptionTextBox.Style.Font.Name = "Arial"
Me.cargoMNCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMNCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cargoMNCaptionTextBox.StyleName = "Caption"
Me.cargoMNCaptionTextBox.Value = "CARGO"
'
'TextBox83
'
Me.TextBox83.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox83.Name = "TextBox83"
Me.TextBox83.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(4.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox83.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.None
Me.TextBox83.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.TextBox83.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Outset
Me.TextBox83.Style.Font.Bold = True
Me.TextBox83.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox83.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox83.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.TextBox83.Value = "IMPORTE EN SOLES"
'
'glosaCaptionTextBox
'
Me.glosaCaptionTextBox.CanGrow = True
Me.glosaCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaCaptionTextBox.Name = "glosaCaptionTextBox"
Me.glosaCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(5.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.glosaCaptionTextBox.Style.Font.Name = "Arial"
Me.glosaCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.glosaCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.glosaCaptionTextBox.StyleName = "Caption"
Me.glosaCaptionTextBox.Value = "GLOSA"
'
'fechaDocumentoCaptionTextBox
'
Me.fechaDocumentoCaptionTextBox.CanGrow = True
Me.fechaDocumentoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fechaDocumentoCaptionTextBox.Name = "fechaDocumentoCaptionTextBox"
Me.fechaDocumentoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fechaDocumentoCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.fechaDocumentoCaptionTextBox.Style.Font.Name = "Arial"
Me.fechaDocumentoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.fechaDocumentoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.fechaDocumentoCaptionTextBox.StyleName = "Caption"
Me.fechaDocumentoCaptionTextBox.Value = "FECHA"
'
'rucCaptionTextBox
'
Me.rucCaptionTextBox.CanGrow = True
Me.rucCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucCaptionTextBox.Name = "rucCaptionTextBox"
Me.rucCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.rucCaptionTextBox.Style.Font.Name = "Arial"
Me.rucCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.rucCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.rucCaptionTextBox.StyleName = "Caption"
Me.rucCaptionTextBox.Value = "RUC"
'
'nroChequeCaptionTextBox
'
Me.nroChequeCaptionTextBox.CanGrow = True
Me.nroChequeCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(3.9952082633972168R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroChequeCaptionTextBox.Name = "nroChequeCaptionTextBox"
Me.nroChequeCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroChequeCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.nroChequeCaptionTextBox.Style.Font.Name = "Arial"
Me.nroChequeCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.nroChequeCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.nroChequeCaptionTextBox.StyleName = "Caption"
Me.nroChequeCaptionTextBox.Value = "N° CHEQUE"
'
'codigoCaptionTextBox
'
Me.codigoCaptionTextBox.CanGrow = True
Me.codigoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.codigoCaptionTextBox.Name = "codigoCaptionTextBox"
Me.codigoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.codigoCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.codigoCaptionTextBox.Style.Font.Name = "Arial"
Me.codigoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.codigoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.codigoCaptionTextBox.StyleName = "Caption"
Me.codigoCaptionTextBox.Value = "COMPROB."
'
'idSubDiarioCaptionTextBox
'
Me.idSubDiarioCaptionTextBox.CanGrow = True
Me.idSubDiarioCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.idSubDiarioCaptionTextBox.Name = "idSubDiarioCaptionTextBox"
Me.idSubDiarioCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.idSubDiarioCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.idSubDiarioCaptionTextBox.Style.Font.Name = "Arial"
Me.idSubDiarioCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.idSubDiarioCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.idSubDiarioCaptionTextBox.StyleName = "Caption"
Me.idSubDiarioCaptionTextBox.Value = "S.D."
'
'razonSocialCaptionTextBox
'
Me.razonSocialCaptionTextBox.CanGrow = True
Me.razonSocialCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(8.9958333969116211R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialCaptionTextBox.Name = "razonSocialCaptionTextBox"
Me.razonSocialCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(5.9997992515563965R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialCaptionTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid
Me.razonSocialCaptionTextBox.Style.Font.Name = "Arial"
Me.razonSocialCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.razonSocialCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.razonSocialCaptionTextBox.StyleName = "Caption"
Me.razonSocialCaptionTextBox.Value = "RAZON SOCIAL"
'
'TextBox10
'
Me.TextBox10.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox10.Name = "TextBox10"
Me.TextBox10.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(5.5000004768371582R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox10.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.None
Me.TextBox10.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.None
Me.TextBox10.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.None
Me.TextBox10.Style.Font.Bold = False
Me.TextBox10.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox10.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox10.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.TextBox10.Value = "SALDO INICIAL:"
'
'TextBox9
'
Me.TextBox9.CanGrow = True
Me.TextBox9.Format = "{0:N2}"
Me.TextBox9.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox9.Name = "TextBox9"
Me.TextBox9.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox9.Style.Font.Name = "Arial"
Me.TextBox9.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox9.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox9.StyleName = "Data"
Me.TextBox9.Value = "= Fields.SaldoDeudorMN"
'
'TextBox8
'
Me.TextBox8.CanGrow = True
Me.TextBox8.Format = "{0:N2}"
Me.TextBox8.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox8.Name = "TextBox8"
Me.TextBox8.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox8.Style.Font.Name = "Arial"
Me.TextBox8.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox8.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox8.StyleName = "Data"
Me.TextBox8.Value = "= Fields.SaldoAcreedorMN"
'
'TextBox7
'
Me.TextBox7.CanGrow = True
Me.TextBox7.Format = "{0:N2}"
Me.TextBox7.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox7.Name = "TextBox7"
Me.TextBox7.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox7.Style.Font.Name = "Arial"
Me.TextBox7.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox7.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox7.StyleName = "Data"
Me.TextBox7.Value = "= Fields.SaldoDeudorME"
'
'TextBox6
'
Me.TextBox6.CanGrow = True
Me.TextBox6.Format = "{0:N2}"
Me.TextBox6.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0099999904632568R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox6.Name = "TextBox6"
Me.TextBox6.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox6.Style.Font.Name = "Arial"
Me.TextBox6.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox6.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox6.StyleName = "Data"
Me.TextBox6.Value = "= Fields.SaldoAcreedorME"
'
'cuentaDataTextBox
'
Me.cuentaDataTextBox.CanGrow = True
Me.cuentaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Name = "cuentaDataTextBox"
Me.cuentaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(14.999799728393555R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Style.Font.Name = "Arial"
Me.cuentaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cuentaDataTextBox.StyleName = "Data"
Me.cuentaDataTextBox.Value = "=Fields.Cuenta+' '+ Fields.Descripcion"
'
'cuentaGroupFooter
'
Me.cuentaGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.cuentaGroupFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.abonoMESumFunctionTextBox, Me.cargoMESumFunctionTextBox, Me.abonoMNSumFunctionTextBox, Me.cargoMNSumFunctionTextBox, Me.TextBox2, Me.TextBox5, Me.TextBox17, Me.TextBox20, Me.TextBox21, Me.TextBox22})
Me.cuentaGroupFooter.Name = "cuentaGroupFooter"
'
'cuentaGroup
'
Me.cuentaGroup.GroupFooter = Me.cuentaGroupFooter
Me.cuentaGroup.GroupHeader = Me.cuentaGroupHeader
Me.cuentaGroup.Groupings.AddRange(New Telerik.Reporting.Grouping() {New Telerik.Reporting.Grouping("=Fields.Cuenta")})
Me.cuentaGroup.Name = "cuentaGroup"
'
'reportFooter
'
Me.reportFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportFooter.Name = "reportFooter"
Me.reportFooter.Style.Visible = True
'
'pageHeader
'
Me.pageHeader.Height = New Telerik.Reporting.Drawing.Unit(3.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox29, Me.TextBox12, Me.TextBox13, Me.TextBox14, Me.TextBox15, Me.TextBox16, Me.TextBox28, Me.TextBox31, Me.TextBox30, Me.titleTextBox, Me.TextBox41})
Me.pageHeader.Name = "pageHeader"
'
'TextBox29
'
Me.TextBox29.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox29.Name = "TextBox29"
Me.TextBox29.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox29.Style.Font.Bold = True
Me.TextBox29.Style.Font.Name = "Arial"
Me.TextBox29.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(9.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox29.StyleName = "PageInfo"
Me.TextBox29.Value = "FONCREAGRO"
'
'TextBox12
'
Me.TextBox12.Format = "{0:d}"
Me.TextBox12.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5027083158493042R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox12.Name = "TextBox12"
Me.TextBox12.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0000014305114746R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox12.Style.Font.Name = "Arial"
Me.TextBox12.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox12.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox12.StyleName = "PageInfo"
Me.TextBox12.Value = "=PageNumber"
'
'TextBox13
'
Me.TextBox13.Format = "{0:d}"
Me.TextBox13.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.500415802001953R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5027083158493042R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox13.Name = "TextBox13"
Me.TextBox13.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9995981454849243R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox13.Style.Font.Name = "Arial"
Me.TextBox13.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox13.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox13.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox13.StyleName = "PageInfo"
Me.TextBox13.Value = "Fecha:"
'
'TextBox14
'
Me.TextBox14.Format = "{0:d}"
Me.TextBox14.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.500415802001953R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox14.Name = "TextBox14"
Me.TextBox14.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9995981454849243R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox14.Style.Font.Name = "Arial"
Me.TextBox14.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox14.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox14.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox14.StyleName = "PageInfo"
Me.TextBox14.Value = "Página:"
'
'TextBox15
'
Me.TextBox15.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox15.Name = "TextBox15"
Me.TextBox15.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox15.Style.Font.Bold = True
Me.TextBox15.Style.Font.Name = "Arial"
Me.TextBox15.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(9.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox15.StyleName = "PageInfo"
Me.TextBox15.Value = "Jr. Ciro Alegría N° 296 - Cajamarca"
'
'TextBox16
'
Me.TextBox16.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5027083158493042R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox16.Name = "TextBox16"
Me.TextBox16.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox16.Style.Font.Bold = True
Me.TextBox16.Style.Font.Name = "Arial"
Me.TextBox16.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(9.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox16.StyleName = "PageInfo"
Me.TextBox16.Value = "RUC: 20453262767"
'
'TextBox28
'
Me.TextBox28.Format = "{0:d}"
Me.TextBox28.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox28.Name = "TextBox28"
Me.TextBox28.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0000014305114746R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox28.Style.Font.Name = "Arial"
Me.TextBox28.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox28.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox28.StyleName = "PageInfo"
Me.TextBox28.Value = "=PageNumber"
'
'TextBox31
'
Me.TextBox31.Format = "{0:T}"
Me.TextBox31.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox31.Name = "TextBox31"
Me.TextBox31.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0000014305114746R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox31.Style.Font.Name = "Arial"
Me.TextBox31.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox31.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox31.StyleName = "PageInfo"
Me.TextBox31.Value = "=NOW()"
'
'TextBox30
'
Me.TextBox30.Format = "{0:d}"
Me.TextBox30.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.500415802001953R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox30.Name = "TextBox30"
Me.TextBox30.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9995981454849243R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox30.Style.Font.Name = "Arial"
Me.TextBox30.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox30.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox30.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox30.StyleName = "PageInfo"
Me.TextBox30.Value = "Hora:"
'
'titleTextBox
'
Me.titleTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.titleTextBox.Name = "titleTextBox"
Me.titleTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(28.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.50000017881393433R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.titleTextBox.Style.Font.Bold = True
Me.titleTextBox.Style.Font.Name = "Arial"
Me.titleTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(10.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.titleTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.titleTextBox.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Top
Me.titleTextBox.StyleName = "Title"
Me.titleTextBox.Value = "MOVIMIENTOS DETALLADOS DE LAS CUENTAS"
'
'TextBox41
'
Me.TextBox41.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox41.Name = "TextBox41"
Me.TextBox41.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(28.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox41.Style.Font.Bold = True
Me.TextBox41.Style.Font.Name = "Arial"
Me.TextBox41.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox41.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox41.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Top
Me.TextBox41.StyleName = "Title"
Me.TextBox41.Value = resources.GetString("TextBox41.Value")
'
'pageFooter
'
Me.pageFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageFooter.Name = "pageFooter"
'
'reportHeader
'
Me.reportHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportHeader.Name = "reportHeader"
Me.reportHeader.Style.Visible = False
'
'detail
'
Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.detail.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox11, Me.abonoMEDataTextBox, Me.cargoMEDataTextBox, Me.abonoMNDataTextBox, Me.cargoMNDataTextBox, Me.glosaDataTextBox, Me.razonSocialDataTextBox, Me.rucDataTextBox, Me.nroChequeDataTextBox, Me.codigoDataTextBox, Me.idSubDiarioDataTextBox, Me.fechaDocumentoDataTextBox})
Me.detail.Name = "detail"
'
'TextBox11
'
Me.TextBox11.CanGrow = True
Me.TextBox11.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox11.Name = "TextBox11"
Me.TextBox11.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox11.Style.Font.Name = "Arial"
Me.TextBox11.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox11.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox11.StyleName = "Data"
Me.TextBox11.Value = "= Substr(Fields.Proyecto,0,4)"
'
'abonoMEDataTextBox
'
Me.abonoMEDataTextBox.CanGrow = True
Me.abonoMEDataTextBox.Format = "{0:N2}"
Me.abonoMEDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMEDataTextBox.Name = "abonoMEDataTextBox"
Me.abonoMEDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMEDataTextBox.Style.Font.Name = "Arial"
Me.abonoMEDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMEDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.abonoMEDataTextBox.StyleName = "Data"
Me.abonoMEDataTextBox.Value = "=Fields.AbonoME"
'
'cargoMEDataTextBox
'
Me.cargoMEDataTextBox.CanGrow = True
Me.cargoMEDataTextBox.Format = "{0:N2}"
Me.cargoMEDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMEDataTextBox.Name = "cargoMEDataTextBox"
Me.cargoMEDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMEDataTextBox.Style.Font.Name = "Arial"
Me.cargoMEDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMEDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.cargoMEDataTextBox.StyleName = "Data"
Me.cargoMEDataTextBox.Value = "=Fields.CargoME"
'
'abonoMNDataTextBox
'
Me.abonoMNDataTextBox.CanGrow = True
Me.abonoMNDataTextBox.Format = "{0:N2}"
Me.abonoMNDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.500001907348633R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNDataTextBox.Name = "abonoMNDataTextBox"
Me.abonoMNDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNDataTextBox.Style.Font.Name = "Arial"
Me.abonoMNDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMNDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.abonoMNDataTextBox.StyleName = "Data"
Me.abonoMNDataTextBox.Value = "=Fields.AbonoMN"
'
'cargoMNDataTextBox
'
Me.cargoMNDataTextBox.CanGrow = True
Me.cargoMNDataTextBox.Format = "{0:N2}"
Me.cargoMNDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNDataTextBox.Name = "cargoMNDataTextBox"
Me.cargoMNDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNDataTextBox.Style.Font.Name = "Arial"
Me.cargoMNDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMNDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.cargoMNDataTextBox.StyleName = "Data"
Me.cargoMNDataTextBox.Value = "=Fields.CargoMN"
'
'glosaDataTextBox
'
Me.glosaDataTextBox.CanGrow = True
Me.glosaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaDataTextBox.Name = "glosaDataTextBox"
Me.glosaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(5.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaDataTextBox.Style.Font.Name = "Arial"
Me.glosaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.glosaDataTextBox.StyleName = "Data"
Me.glosaDataTextBox.Value = "=Fields.Glosa"
'
'razonSocialDataTextBox
'
Me.razonSocialDataTextBox.CanGrow = True
Me.razonSocialDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(8.9958333969116211R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialDataTextBox.Name = "razonSocialDataTextBox"
Me.razonSocialDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(5.9997992515563965R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialDataTextBox.Style.Font.Name = "Arial"
Me.razonSocialDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.razonSocialDataTextBox.StyleName = "Data"
Me.razonSocialDataTextBox.Value = "=Fields.RazonSocial"
'
'rucDataTextBox
'
Me.rucDataTextBox.CanGrow = True
Me.rucDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucDataTextBox.Name = "rucDataTextBox"
Me.rucDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucDataTextBox.Style.Font.Name = "Arial"
Me.rucDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.rucDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.rucDataTextBox.StyleName = "Data"
Me.rucDataTextBox.Value = "=Fields.Ruc"
'
'nroChequeDataTextBox
'
Me.nroChequeDataTextBox.CanGrow = True
Me.nroChequeDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(3.9952082633972168R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroChequeDataTextBox.Name = "nroChequeDataTextBox"
Me.nroChequeDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroChequeDataTextBox.Style.Font.Name = "Arial"
Me.nroChequeDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.nroChequeDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.nroChequeDataTextBox.StyleName = "Data"
Me.nroChequeDataTextBox.Value = "=Fields.NroCheque"
'
'codigoDataTextBox
'
Me.codigoDataTextBox.CanGrow = True
Me.codigoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.codigoDataTextBox.Name = "codigoDataTextBox"
Me.codigoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.codigoDataTextBox.Style.Font.Name = "Arial"
Me.codigoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.codigoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.codigoDataTextBox.StyleName = "Data"
Me.codigoDataTextBox.Value = "=Fields.Codigo"
'
'idSubDiarioDataTextBox
'
Me.idSubDiarioDataTextBox.CanGrow = True
Me.idSubDiarioDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.idSubDiarioDataTextBox.Name = "idSubDiarioDataTextBox"
Me.idSubDiarioDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.idSubDiarioDataTextBox.Style.Font.Name = "Arial"
Me.idSubDiarioDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.idSubDiarioDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.idSubDiarioDataTextBox.StyleName = "Data"
Me.idSubDiarioDataTextBox.Value = "=Fields.IdSubDiario"
'
'fechaDocumentoDataTextBox
'
Me.fechaDocumentoDataTextBox.CanGrow = True
Me.fechaDocumentoDataTextBox.Format = "{0:d}"
Me.fechaDocumentoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fechaDocumentoDataTextBox.Name = "fechaDocumentoDataTextBox"
Me.fechaDocumentoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fechaDocumentoDataTextBox.Style.Font.Name = "Arial"
Me.fechaDocumentoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.fechaDocumentoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.fechaDocumentoDataTextBox.StyleName = "Data"
Me.fechaDocumentoDataTextBox.Value = "=Fields.FechaDocumento"
'
'abonoMESumFunctionTextBox
'
Me.abonoMESumFunctionTextBox.CanGrow = True
Me.abonoMESumFunctionTextBox.Format = "{0:N2}"
Me.abonoMESumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMESumFunctionTextBox.Name = "abonoMESumFunctionTextBox"
Me.abonoMESumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMESumFunctionTextBox.Style.Font.Name = "Arial"
Me.abonoMESumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMESumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.abonoMESumFunctionTextBox.StyleName = "Data"
Me.abonoMESumFunctionTextBox.Value = "=Sum(Fields.AbonoME)"
'
'cargoMESumFunctionTextBox
'
Me.cargoMESumFunctionTextBox.CanGrow = True
Me.cargoMESumFunctionTextBox.Format = "{0:N2}"
Me.cargoMESumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMESumFunctionTextBox.Name = "cargoMESumFunctionTextBox"
Me.cargoMESumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMESumFunctionTextBox.Style.Font.Name = "Arial"
Me.cargoMESumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMESumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.cargoMESumFunctionTextBox.StyleName = "Data"
Me.cargoMESumFunctionTextBox.Value = "=Sum(Fields.CargoME)"
'
'abonoMNSumFunctionTextBox
'
Me.abonoMNSumFunctionTextBox.CanGrow = True
Me.abonoMNSumFunctionTextBox.Format = "{0:N2}"
Me.abonoMNSumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.500001907348633R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNSumFunctionTextBox.Name = "abonoMNSumFunctionTextBox"
Me.abonoMNSumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.abonoMNSumFunctionTextBox.Style.Font.Name = "Arial"
Me.abonoMNSumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.abonoMNSumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.abonoMNSumFunctionTextBox.StyleName = "Data"
Me.abonoMNSumFunctionTextBox.Value = "=Sum(Fields.AbonoMN)"
'
'cargoMNSumFunctionTextBox
'
Me.cargoMNSumFunctionTextBox.CanGrow = True
Me.cargoMNSumFunctionTextBox.Format = "{0:N2}"
Me.cargoMNSumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNSumFunctionTextBox.Name = "cargoMNSumFunctionTextBox"
Me.cargoMNSumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cargoMNSumFunctionTextBox.Style.Font.Name = "Arial"
Me.cargoMNSumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cargoMNSumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.cargoMNSumFunctionTextBox.StyleName = "Data"
Me.cargoMNSumFunctionTextBox.Value = "=Sum(Fields.CargoMN)"
'
'TextBox2
'
Me.TextBox2.CanGrow = True
Me.TextBox2.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Style.Font.Name = "Arial"
Me.TextBox2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox2.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox2.StyleName = "Caption"
Me.TextBox2.Value = "SUMAS DEL MES:"
'
'TextBox5
'
Me.TextBox5.CanGrow = True
Me.TextBox5.Format = "{0:N2}"
Me.TextBox5.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(26.500202178955078R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox5.Name = "TextBox5"
Me.TextBox5.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.99979829788208R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox5.Style.Font.Name = "Arial"
Me.TextBox5.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox5.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox5.StyleName = "Data"
Me.TextBox5.Value = resources.GetString("TextBox5.Value")
'
'TextBox17
'
Me.TextBox17.CanGrow = True
Me.TextBox17.Format = "{0:N2}"
Me.TextBox17.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.500402450561523R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox17.Name = "TextBox17"
Me.TextBox17.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9995981454849243R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox17.Style.Font.Name = "Arial"
Me.TextBox17.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox17.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox17.StyleName = "Data"
Me.TextBox17.Value = resources.GetString("TextBox17.Value")
'
'TextBox20
'
Me.TextBox20.CanGrow = True
Me.TextBox20.Format = "{0:N2}"
Me.TextBox20.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.500402450561523R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox20.Name = "TextBox20"
Me.TextBox20.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9995981454849243R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox20.Style.Font.Name = "Arial"
Me.TextBox20.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox20.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox20.StyleName = "Data"
Me.TextBox20.Value = resources.GetString("TextBox20.Value")
'
'TextBox21
'
Me.TextBox21.CanGrow = True
Me.TextBox21.Format = "{0:N2}"
Me.TextBox21.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.500202178955078R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox21.Name = "TextBox21"
Me.TextBox21.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.99979829788208R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox21.Style.Font.Name = "Arial"
Me.TextBox21.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox21.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox21.StyleName = "Data"
Me.TextBox21.Value = resources.GetString("TextBox21.Value")
'
'TextBox22
'
Me.TextBox22.CanGrow = True
Me.TextBox22.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox22.Name = "TextBox22"
Me.TextBox22.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(20.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox22.Style.Font.Name = "Arial"
Me.TextBox22.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox22.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox22.StyleName = "Caption"
Me.TextBox22.Value = "SALDO ACTUAL: "
'
'RepMovCuentas
'
Me.DataSource = Me.SDSRepMovCuentas
Me.Groups.AddRange(New Telerik.Reporting.Group() {Me.labelsGroup, Me.cuentaGroup})
Me.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.labelsGroupHeader, Me.labelsGroupFooter, Me.cuentaGroupHeader, Me.cuentaGroupFooter, Me.reportFooter, Me.pageHeader, Me.pageFooter, Me.reportHeader, Me.detail})
Me.PageSettings.Landscape = True
Me.PageSettings.Margins.Bottom = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Left = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Right = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Top = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.A4
ReportParameter1.Name = "Fecha"
ReportParameter1.Text = "Fecha"
ReportParameter1.Type = Telerik.Reporting.ReportParameterType.DateTime
ReportParameter1.Visible = True
ReportParameter2.Name = "idProyecto"
ReportParameter2.Text = "idProyecto"
ReportParameter2.Type = Telerik.Reporting.ReportParameterType.[Integer]
ReportParameter2.Visible = True
ReportParameter3.Name = "CuentaInicio"
ReportParameter3.Text = "CuentaInicio"
ReportParameter3.Visible = True
ReportParameter4.Name = "CuentaFin"
ReportParameter4.Text = "CuentaFin"
ReportParameter4.Visible = True
Me.ReportParameters.Add(ReportParameter1)
Me.ReportParameters.Add(ReportParameter2)
Me.ReportParameters.Add(ReportParameter3)
Me.ReportParameters.Add(ReportParameter4)
Me.Style.BackgroundColor = System.Drawing.Color.White
StyleRule1.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Title")})
StyleRule1.Style.Color = System.Drawing.Color.Black
StyleRule1.Style.Font.Bold = True
StyleRule1.Style.Font.Italic = False
StyleRule1.Style.Font.Name = "Tahoma"
StyleRule1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule1.Style.Font.Strikeout = False
StyleRule1.Style.Font.Underline = False
StyleRule2.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Caption")})
StyleRule2.Style.Color = System.Drawing.Color.Black
StyleRule2.Style.Font.Name = "Tahoma"
StyleRule2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule2.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule3.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Data")})
StyleRule3.Style.Font.Name = "Tahoma"
StyleRule3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule3.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule4.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("PageInfo")})
StyleRule4.Style.Font.Name = "Tahoma"
StyleRule4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.StyleSheet.AddRange(New Telerik.Reporting.Drawing.StyleRule() {StyleRule1, StyleRule2, StyleRule3, StyleRule4})
Me.Width = New Telerik.Reporting.Drawing.Unit(28.5R, Telerik.Reporting.Drawing.UnitType.Cm)
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents SDSRepMovCuentas As Telerik.Reporting.SqlDataSource
Friend WithEvents labelsGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents labelsGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents labelsGroup As Telerik.Reporting.Group
Friend WithEvents cuentaGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents cuentaGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents cuentaGroup As Telerik.Reporting.Group
Friend WithEvents reportFooter As Telerik.Reporting.ReportFooterSection
Friend WithEvents pageHeader As Telerik.Reporting.PageHeaderSection
Friend WithEvents pageFooter As Telerik.Reporting.PageFooterSection
Friend WithEvents reportHeader As Telerik.Reporting.ReportHeaderSection
Friend WithEvents detail As Telerik.Reporting.DetailSection
Friend WithEvents TextBox29 As Telerik.Reporting.TextBox
Friend WithEvents TextBox12 As Telerik.Reporting.TextBox
Friend WithEvents TextBox13 As Telerik.Reporting.TextBox
Friend WithEvents TextBox14 As Telerik.Reporting.TextBox
Friend WithEvents TextBox15 As Telerik.Reporting.TextBox
Friend WithEvents TextBox16 As Telerik.Reporting.TextBox
Friend WithEvents TextBox28 As Telerik.Reporting.TextBox
Friend WithEvents TextBox31 As Telerik.Reporting.TextBox
Friend WithEvents TextBox30 As Telerik.Reporting.TextBox
Friend WithEvents titleTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox41 As Telerik.Reporting.TextBox
Friend WithEvents TextBox3 As Telerik.Reporting.TextBox
Friend WithEvents abonoMECaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMECaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox4 As Telerik.Reporting.TextBox
Friend WithEvents abonoMNCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMNCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox83 As Telerik.Reporting.TextBox
Friend WithEvents glosaCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents fechaDocumentoCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents rucCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents nroChequeCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents codigoCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents idSubDiarioCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents razonSocialCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox10 As Telerik.Reporting.TextBox
Friend WithEvents TextBox9 As Telerik.Reporting.TextBox
Friend WithEvents TextBox8 As Telerik.Reporting.TextBox
Friend WithEvents TextBox7 As Telerik.Reporting.TextBox
Friend WithEvents TextBox6 As Telerik.Reporting.TextBox
Friend WithEvents cuentaDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox11 As Telerik.Reporting.TextBox
Friend WithEvents abonoMEDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMEDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents abonoMNDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMNDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents glosaDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents razonSocialDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents rucDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents nroChequeDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents codigoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents idSubDiarioDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents fechaDocumentoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents abonoMESumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMESumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents abonoMNSumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cargoMNSumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox2 As Telerik.Reporting.TextBox
Friend WithEvents TextBox5 As Telerik.Reporting.TextBox
Friend WithEvents TextBox17 As Telerik.Reporting.TextBox
Friend WithEvents TextBox20 As Telerik.Reporting.TextBox
Friend WithEvents TextBox21 As Telerik.Reporting.TextBox
Friend WithEvents TextBox22 As Telerik.Reporting.TextBox
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.Report/RepMovCuentas.Designer.vb
|
Visual Basic
|
mit
| 74,612
|
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Imports System.Runtime.Serialization
Imports Newtonsoft.Json
<JsonObject(MemberSerialization.OptIn)>
<DataContract>
Public Class LampProfile
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Private _username As String
''' <summary>
''' The username of the person, used to login
''' </summary>
''' <returns></returns>
<JsonProperty("username")>
<DataMember>
Public Property Username As String
Get
Return _username
End Get
Set(value As String)
_username = value
NotifyPropertyChanged()
End Set
End Property
Private _name As String
''' <summary>
''' The full name of the person
''' </summary>
''' <returns></returns>
<JsonProperty("name")>
<DataMember>
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
NotifyPropertyChanged()
End Set
End Property
Private _userid As String
''' <summary>
''' user guid
''' </summary>
''' <returns></returns>
<JsonProperty("userId")>
<DataMember>
Public Property UserId As String
Get
Return _userid
End Get
Set(value As String)
_userid = value
NotifyPropertyChanged()
End Set
End Property
Private _permissionLevel As UserPermission
<JsonProperty("permissionLevel")>
<DataMember>
Public Property PermissionLevel As UserPermission
Get
Return _permissionLevel
End Get
Set(value As UserPermission)
_permissionLevel = value
NotifyPropertyChanged()
End Set
End Property
''' <summary>
''' constructor for <see cref="LampProfile"></see>
''' </summary>
''' <param name="username"></param>
''' <param name="name"></param>
''' <param name="userid"></param>
Sub New(username As String, name As String, userid As String, permissionLevel As UserPermission)
Me.Username = username
Me.Name = name
Me.UserId = userid
Me.PermissionLevel = permissionLevel
End Sub
End Class
|
KameQuazi/Software-Major-Assignment-2k18
|
LampCommon/user/LampProfile.vb
|
Visual Basic
|
mit
| 2,580
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class ListeClients
Inherits System.Windows.Forms.Form
'Form remplace la méthode Dispose pour nettoyer la liste des composants.
<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
'Requise par le Concepteur Windows Form
Private components As System.ComponentModel.IContainer
'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form
'Elle peut être modifiée à l'aide du Concepteur Windows Form.
'Ne la modifiez pas à l'aide de l'éditeur de code.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(ListeClients))
Me.PanelContainer = New System.Windows.Forms.Panel()
Me.btnShow = New System.Windows.Forms.Button()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.btnPrint = New System.Windows.Forms.Button()
Me.btnAdd = New System.Windows.Forms.Button()
Me.txtNom = New System.Windows.Forms.TextBox()
Me.labelProduitCF = New System.Windows.Forms.Label()
Me.btnEdit = New System.Windows.Forms.Button()
Me.ListClient = New System.Windows.Forms.ListView()
Me.ColumnHeader1 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ColumnHeader2 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ColumnHeader3 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ColumnHeader4 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ColumnHeader5 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ColumnHeader6 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components)
Me.RapportDesAchatsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.btnDelete = New System.Windows.Forms.Button()
Me.RadialPanel1 = New HG.UI.RadialPanel()
Me.Label1 = New System.Windows.Forms.Label()
Me.PanelContainer.SuspendLayout()
Me.GroupBox1.SuspendLayout()
Me.ContextMenuStrip1.SuspendLayout()
Me.RadialPanel1.SuspendLayout()
Me.SuspendLayout()
'
'PanelContainer
'
Me.PanelContainer.BackColor = System.Drawing.Color.Transparent
Me.PanelContainer.Controls.Add(Me.btnShow)
Me.PanelContainer.Controls.Add(Me.GroupBox1)
Me.PanelContainer.Controls.Add(Me.btnEdit)
Me.PanelContainer.Controls.Add(Me.ListClient)
Me.PanelContainer.Controls.Add(Me.btnDelete)
Me.PanelContainer.Controls.Add(Me.RadialPanel1)
Me.PanelContainer.Location = New System.Drawing.Point(23, 12)
Me.PanelContainer.Name = "PanelContainer"
Me.PanelContainer.Size = New System.Drawing.Size(1154, 636)
Me.PanelContainer.TabIndex = 0
'
'btnShow
'
Me.btnShow.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer))
Me.btnShow.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnShow.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnShow.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnShow.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnShow.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnShow.Font = New System.Drawing.Font("Consolas", 10.0!)
Me.btnShow.ForeColor = System.Drawing.Color.White
Me.btnShow.Location = New System.Drawing.Point(298, 569)
Me.btnShow.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.btnShow.Name = "btnShow"
Me.btnShow.Size = New System.Drawing.Size(181, 54)
Me.btnShow.TabIndex = 19
Me.btnShow.Text = "Afficher"
Me.btnShow.UseVisualStyleBackColor = False
'
'GroupBox1
'
Me.GroupBox1.BackColor = System.Drawing.Color.Transparent
Me.GroupBox1.Controls.Add(Me.btnPrint)
Me.GroupBox1.Controls.Add(Me.btnAdd)
Me.GroupBox1.Controls.Add(Me.txtNom)
Me.GroupBox1.Controls.Add(Me.labelProduitCF)
Me.GroupBox1.ForeColor = System.Drawing.Color.White
Me.GroupBox1.Location = New System.Drawing.Point(3, 49)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(1148, 62)
Me.GroupBox1.TabIndex = 73
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Filtres"
'
'btnPrint
'
Me.btnPrint.BackColor = System.Drawing.Color.FromArgb(CType(CType(120, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(171, Byte), Integer))
Me.btnPrint.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnPrint.Font = New System.Drawing.Font("Consolas", 11.0!)
Me.btnPrint.Image = Global.HG.My.Resources.Resources.printer
Me.btnPrint.Location = New System.Drawing.Point(1068, 10)
Me.btnPrint.Name = "btnPrint"
Me.btnPrint.Size = New System.Drawing.Size(64, 49)
Me.btnPrint.TabIndex = 18
Me.btnPrint.UseVisualStyleBackColor = False
'
'btnAdd
'
Me.btnAdd.BackColor = System.Drawing.Color.FromArgb(CType(CType(120, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(171, Byte), Integer))
Me.btnAdd.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnAdd.Font = New System.Drawing.Font("Consolas", 11.0!)
Me.btnAdd.Image = Global.HG.My.Resources.Resources.add
Me.btnAdd.Location = New System.Drawing.Point(1002, 11)
Me.btnAdd.Name = "btnAdd"
Me.btnAdd.Size = New System.Drawing.Size(63, 49)
Me.btnAdd.TabIndex = 17
Me.btnAdd.UseVisualStyleBackColor = False
'
'txtNom
'
Me.txtNom.Location = New System.Drawing.Point(197, 23)
Me.txtNom.Name = "txtNom"
Me.txtNom.Size = New System.Drawing.Size(594, 26)
Me.txtNom.TabIndex = 3
'
'labelProduitCF
'
Me.labelProduitCF.AutoSize = True
Me.labelProduitCF.ForeColor = System.Drawing.Color.White
Me.labelProduitCF.Location = New System.Drawing.Point(57, 29)
Me.labelProduitCF.Name = "labelProduitCF"
Me.labelProduitCF.Size = New System.Drawing.Size(127, 19)
Me.labelProduitCF.TabIndex = 1
Me.labelProduitCF.Text = "Nom ou prenom :"
'
'btnEdit
'
Me.btnEdit.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer))
Me.btnEdit.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnEdit.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnEdit.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnEdit.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnEdit.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnEdit.Font = New System.Drawing.Font("Consolas", 10.0!)
Me.btnEdit.ForeColor = System.Drawing.Color.White
Me.btnEdit.Image = CType(resources.GetObject("btnEdit.Image"), System.Drawing.Image)
Me.btnEdit.Location = New System.Drawing.Point(487, 569)
Me.btnEdit.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.btnEdit.Name = "btnEdit"
Me.btnEdit.Size = New System.Drawing.Size(181, 54)
Me.btnEdit.TabIndex = 20
Me.btnEdit.Text = "Modifier"
Me.btnEdit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText
Me.btnEdit.UseVisualStyleBackColor = False
'
'ListClient
'
Me.ListClient.Activation = System.Windows.Forms.ItemActivation.TwoClick
Me.ListClient.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2, Me.ColumnHeader3, Me.ColumnHeader4, Me.ColumnHeader5, Me.ColumnHeader6})
Me.ListClient.ContextMenuStrip = Me.ContextMenuStrip1
Me.ListClient.Font = New System.Drawing.Font("Open Sans", 11.0!)
Me.ListClient.FullRowSelect = True
Me.ListClient.GridLines = True
Me.ListClient.Location = New System.Drawing.Point(0, 114)
Me.ListClient.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.ListClient.MultiSelect = False
Me.ListClient.Name = "ListClient"
Me.ListClient.Size = New System.Drawing.Size(1153, 450)
Me.ListClient.TabIndex = 69
Me.ListClient.UseCompatibleStateImageBehavior = False
Me.ListClient.View = System.Windows.Forms.View.Details
'
'ColumnHeader1
'
Me.ColumnHeader1.Text = "id"
Me.ColumnHeader1.Width = 0
'
'ColumnHeader2
'
Me.ColumnHeader2.Text = "Nom"
Me.ColumnHeader2.Width = 231
'
'ColumnHeader3
'
Me.ColumnHeader3.Text = "Prenom"
Me.ColumnHeader3.Width = 189
'
'ColumnHeader4
'
Me.ColumnHeader4.Text = "Tel. 1 "
Me.ColumnHeader4.Width = 195
'
'ColumnHeader5
'
Me.ColumnHeader5.Text = "Tel. 2"
Me.ColumnHeader5.Width = 195
'
'ColumnHeader6
'
Me.ColumnHeader6.Text = "Adresse"
Me.ColumnHeader6.Width = 321
'
'ContextMenuStrip1
'
Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.RapportDesAchatsToolStripMenuItem})
Me.ContextMenuStrip1.Name = "ContextMenuStrip1"
Me.ContextMenuStrip1.Size = New System.Drawing.Size(178, 26)
'
'RapportDesAchatsToolStripMenuItem
'
Me.RapportDesAchatsToolStripMenuItem.Name = "RapportDesAchatsToolStripMenuItem"
Me.RapportDesAchatsToolStripMenuItem.Size = New System.Drawing.Size(177, 22)
Me.RapportDesAchatsToolStripMenuItem.Text = "Rapport des achats "
'
'btnDelete
'
Me.btnDelete.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer))
Me.btnDelete.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnDelete.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnDelete.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnDelete.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(38, Byte), Integer), CType(CType(72, Byte), Integer), CType(CType(84, Byte), Integer))
Me.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnDelete.Font = New System.Drawing.Font("Consolas", 10.0!)
Me.btnDelete.ForeColor = System.Drawing.Color.White
Me.btnDelete.Image = CType(resources.GetObject("btnDelete.Image"), System.Drawing.Image)
Me.btnDelete.Location = New System.Drawing.Point(676, 569)
Me.btnDelete.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.btnDelete.Name = "btnDelete"
Me.btnDelete.Size = New System.Drawing.Size(181, 54)
Me.btnDelete.TabIndex = 21
Me.btnDelete.Text = "Supprimer"
Me.btnDelete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText
Me.btnDelete.UseVisualStyleBackColor = False
'
'RadialPanel1
'
Me.RadialPanel1.Controls.Add(Me.Label1)
Me.RadialPanel1.Location = New System.Drawing.Point(3, 0)
Me.RadialPanel1.Name = "RadialPanel1"
Me.RadialPanel1.Size = New System.Drawing.Size(1151, 53)
Me.RadialPanel1.TabIndex = 68
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.BackColor = System.Drawing.Color.Transparent
Me.Label1.Font = New System.Drawing.Font("Open Sans", 25.0!, System.Drawing.FontStyle.Bold)
Me.Label1.ForeColor = System.Drawing.Color.White
Me.Label1.Location = New System.Drawing.Point(13, 2)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(289, 46)
Me.Label1.TabIndex = 60
Me.Label1.Text = "Liste des clients"
'
'ListeClients
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 18.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.Turquoise
Me.BackgroundImage = Global.HG.My.Resources.Resources.background
Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch
Me.ClientSize = New System.Drawing.Size(1189, 660)
Me.Controls.Add(Me.PanelContainer)
Me.Font = New System.Drawing.Font("Open Sans", 10.0!)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
Me.Name = "ListeClients"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Liste des clients"
Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
Me.PanelContainer.ResumeLayout(False)
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox1.PerformLayout()
Me.ContextMenuStrip1.ResumeLayout(False)
Me.RadialPanel1.ResumeLayout(False)
Me.RadialPanel1.PerformLayout()
Me.ResumeLayout(False)
End Sub
Friend WithEvents PanelContainer As System.Windows.Forms.Panel
Friend WithEvents RadialPanel1 As HG.UI.RadialPanel
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents ListClient As System.Windows.Forms.ListView
Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents labelProduitCF As System.Windows.Forms.Label
Friend WithEvents txtNom As System.Windows.Forms.TextBox
Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader
Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader
Friend WithEvents ColumnHeader3 As System.Windows.Forms.ColumnHeader
Friend WithEvents ColumnHeader4 As System.Windows.Forms.ColumnHeader
Friend WithEvents ColumnHeader5 As System.Windows.Forms.ColumnHeader
Friend WithEvents ColumnHeader6 As System.Windows.Forms.ColumnHeader
Friend WithEvents btnAdd As System.Windows.Forms.Button
Friend WithEvents btnPrint As System.Windows.Forms.Button
Friend WithEvents btnShow As System.Windows.Forms.Button
Friend WithEvents btnEdit As System.Windows.Forms.Button
Friend WithEvents btnDelete As System.Windows.Forms.Button
Friend WithEvents ContextMenuStrip1 As System.Windows.Forms.ContextMenuStrip
Friend WithEvents RapportDesAchatsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
End Class
|
lepresk/HG
|
HG/ListeClients.Designer.vb
|
Visual Basic
|
mit
| 16,390
|
Public Class AudioDeviceList
'Public Shared Devices As ArrayList
Public Shared ActiveDevice As AudioDevice
Shared Sub New()
Try
ActiveDevice = AudioDevice.LoadDevice()
AudioDevice.SaveDevice(ActiveDevice)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
Public Shared Function NextDevice() As AudioDevice
Dim devices As ArrayList
devices = AudioDevices()
If ActiveDevice Is Nothing Then
ActiveDevice = devices(0)
Else
Dim i As Integer
Dim d As AudioDevice
For i = 0 To devices.Count - 1
d = devices(i)
If d.DeviceNumber = ActiveDevice.DeviceNumber Then
If i = devices.Count - 1 Then
ActiveDevice = devices(0)
Else
ActiveDevice = devices(i + 1)
End If
Exit For
End If
Next
End If
AudioDevice.SaveDevice(ActiveDevice)
AudioDevice.EnableDevice(ActiveDevice)
NextDevice = ActiveDevice
End Function
Shared Function AudioDevices() As ArrayList
Dim deviceList As New ArrayList
Dim device As New AudioDevice
EndPointController.Run()
If Not EndPointController.ErrorMessage Is Nothing Then
Throw New Exception("Error running the Endpoint-Controller")
End If
For Each deviceStr In EndPointController.Output
device = AudioDevice.ParseDeviceStr(deviceStr)
deviceList.Add(device)
Next
If deviceList.Count = 0 Then
Throw New Exception("No audio devices found.")
End If
AudioDevices = deviceList
End Function
End Class
|
holli-holzer/adswitch
|
ADSwitch/ADSwitch/AudioDeviceList.vb
|
Visual Basic
|
mit
| 1,857
|
' <auto-generated>
' This code was generated by the .NET ToolStrip Customizer.
' http://toolstripcustomizer.codeplex.com/
' </auto-generated>
Imports System.Drawing
Imports System.Windows.Forms
Namespace LadouceurDark
Class ColorTable
Inherits ProfessionalColorTable
Public Overrides ReadOnly Property ButtonSelectedHighlight() As Color
Get
Return ButtonSelectedGradientMiddle
End Get
End Property
Public Overrides ReadOnly Property ButtonSelectedHighlightBorder() As Color
Get
Return ButtonSelectedBorder
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedHighlight() As Color
Get
Return ButtonPressedGradientMiddle
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedHighlightBorder() As Color
Get
Return ButtonPressedBorder
End Get
End Property
Public Overrides ReadOnly Property ButtonCheckedHighlight() As Color
Get
Return ButtonCheckedGradientMiddle
End Get
End Property
Public Overrides ReadOnly Property ButtonCheckedHighlightBorder() As Color
Get
Return ButtonSelectedBorder
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedBorder() As Color
Get
Return ButtonSelectedBorder
End Get
End Property
Public Overrides ReadOnly Property ButtonSelectedBorder() As Color
Get
Return Color.FromArgb(255, 98, 98, 98)
End Get
End Property
Public Overrides ReadOnly Property ButtonCheckedGradientBegin() As Color
Get
Return Color.FromArgb(255, 144, 144, 144)
End Get
End Property
Public Overrides ReadOnly Property ButtonCheckedGradientMiddle() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonCheckedGradientEnd() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonSelectedGradientBegin() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonSelectedGradientMiddle() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonSelectedGradientEnd() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedGradientBegin() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedGradientMiddle() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property ButtonPressedGradientEnd() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property CheckBackground() As Color
Get
Return Color.FromArgb(255, 173, 173, 173)
End Get
End Property
Public Overrides ReadOnly Property CheckSelectedBackground() As Color
Get
Return Color.FromArgb(255, 173, 173, 173)
End Get
End Property
Public Overrides ReadOnly Property CheckPressedBackground() As Color
Get
Return Color.FromArgb(255, 140, 140, 140)
End Get
End Property
Public Overrides ReadOnly Property GripDark() As Color
Get
Return Color.FromArgb(255, 22, 22, 22)
End Get
End Property
Public Overrides ReadOnly Property GripLight() As Color
Get
Return Color.FromArgb(255, 83, 83, 83)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginGradientBegin() As Color
Get
Return Color.FromArgb(255, 85, 85, 85)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginGradientMiddle() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginGradientEnd() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginRevealedGradientBegin() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginRevealedGradientMiddle() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ImageMarginRevealedGradientEnd() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property MenuStripGradientBegin() As Color
Get
Return Color.FromArgb(255, 138, 138, 138)
End Get
End Property
Public Overrides ReadOnly Property MenuStripGradientEnd() As Color
Get
Return Color.FromArgb(255, 103, 103, 103)
End Get
End Property
Public Overrides ReadOnly Property MenuItemSelected() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property MenuItemBorder() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property MenuBorder() As Color
Get
Return Color.FromArgb(255, 22, 22, 22)
End Get
End Property
Public Overrides ReadOnly Property MenuItemSelectedGradientBegin() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property MenuItemSelectedGradientEnd() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property MenuItemPressedGradientBegin() As Color
Get
Return Color.FromArgb(255, 125, 125, 125)
End Get
End Property
Public Overrides ReadOnly Property MenuItemPressedGradientMiddle() As Color
Get
Return Color.FromArgb(255, 125, 125, 125)
End Get
End Property
Public Overrides ReadOnly Property MenuItemPressedGradientEnd() As Color
Get
Return Color.FromArgb(255, 125, 125, 125)
End Get
End Property
Public Overrides ReadOnly Property RaftingContainerGradientBegin() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property RaftingContainerGradientEnd() As Color
Get
Return Color.FromArgb(255, 170, 170, 170)
End Get
End Property
Public Overrides ReadOnly Property SeparatorDark() As Color
Get
Return Color.FromArgb(255, 22, 22, 22)
End Get
End Property
Public Overrides ReadOnly Property SeparatorLight() As Color
Get
Return Color.FromArgb(255, 62, 62, 62)
End Get
End Property
Public Overrides ReadOnly Property StatusStripGradientBegin() As Color
Get
Return Color.FromArgb(255, 112, 112, 112)
End Get
End Property
Public Overrides ReadOnly Property StatusStripGradientEnd() As Color
Get
Return Color.FromArgb(255, 97, 97, 97)
End Get
End Property
Public Overrides ReadOnly Property ToolStripBorder() As Color
Get
Return Color.FromArgb(255, 22, 22, 22)
End Get
End Property
Public Overrides ReadOnly Property ToolStripDropDownBackground() As Color
Get
Return Color.FromArgb(255, 125, 125, 125)
End Get
End Property
Public Overrides ReadOnly Property ToolStripGradientBegin() As Color
Get
Return Color.FromName("DimGray")
End Get
End Property
Public Overrides ReadOnly Property ToolStripGradientMiddle() As Color
Get
Return Color.FromArgb(255, 89, 89, 89)
End Get
End Property
Public Overrides ReadOnly Property ToolStripGradientEnd() As Color
Get
Return Color.FromArgb(255, 88, 88, 88)
End Get
End Property
Public Overrides ReadOnly Property ToolStripContentPanelGradientBegin() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ToolStripContentPanelGradientEnd() As Color
Get
Return Color.FromArgb(255, 68, 68, 68)
End Get
End Property
Public Overrides ReadOnly Property ToolStripPanelGradientBegin() As Color
Get
Return Color.FromArgb(255, 103, 103, 103)
End Get
End Property
Public Overrides ReadOnly Property ToolStripPanelGradientEnd() As Color
Get
Return Color.FromArgb(255, 103, 103, 103)
End Get
End Property
Public Overrides ReadOnly Property OverflowButtonGradientBegin() As Color
Get
Return Color.FromArgb(255, 103, 103, 103)
End Get
End Property
Public Overrides ReadOnly Property OverflowButtonGradientMiddle() As Color
Get
Return Color.FromArgb(255, 103, 103, 103)
End Get
End Property
Public Overrides ReadOnly Property OverflowButtonGradientEnd() As Color
Get
Return Color.FromArgb(255, 79, 79, 79)
End Get
End Property
End Class
Public Class Renderer
Inherits ToolStripProfessionalRenderer
Public Sub New()
MyBase.New(New ColorTable())
End Sub
End Class
End Namespace
|
shiftosnext/ProjectLadouceur
|
Project_Ladouceur/Ladouceur_Dark.vb
|
Visual Basic
|
apache-2.0
| 11,187
|
' 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("D3D10Tutorial01_WinFormsWindow")>
<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("7c899ee7-8423-4830-8e0e-d222eec3f824")>
' 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/D3D10Tutorial01_WinFormsWindow/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,550
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Friend NotInheritable Class NameAndIndex
Public Sub New(name As String, index As Integer)
Me.Name = name
Me.Index = index
End Sub
Public ReadOnly Name As String
Public ReadOnly Index As Integer
End Class
Friend MustInherit Class AnonymousTypeOrDelegateTemplateSymbol
Inherits InstanceTypeSymbol
Public ReadOnly Manager As AnonymousTypeManager
''' <summary>
''' The name used to emit definition of the type. Will be set when the type's
''' metadata is ready to be emitted, Name property will throw exception if this field
''' is queried before that moment because the name is not defined yet.
''' </summary>
Private _nameAndIndex As NameAndIndex
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private _adjustedPropertyNames As LocationAndNames
#If DEBUG Then
Private _locationAndNamesAreLocked As Boolean
#End If
''' <summary>
''' The key of the anonymous type descriptor used for this type template
''' </summary>
Friend ReadOnly TypeDescriptorKey As String
Protected Sub New(
manager As AnonymousTypeManager,
typeDescr As AnonymousTypeDescriptor
)
Debug.Assert(TypeKind = TypeKind.Class OrElse TypeKind = TypeKind.Delegate)
Me.Manager = manager
Me.TypeDescriptorKey = typeDescr.Key
_adjustedPropertyNames = New LocationAndNames(typeDescr)
Dim arity As Integer = typeDescr.Fields.Length
If TypeKind = TypeKind.Delegate AndAlso typeDescr.Fields.IsSubDescription() Then
' It is a Sub, don't need type parameter for the return type of the Invoke.
arity -= 1
End If
' Create type parameters
If arity = 0 Then
Debug.Assert(TypeKind = TypeKind.Delegate)
Debug.Assert(typeDescr.Parameters.Length = 1)
Debug.Assert(typeDescr.Parameters.IsSubDescription())
_typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty
Else
Dim typeParameters = New TypeParameterSymbol(arity - 1) {}
For ordinal = 0 To arity - 1
typeParameters(ordinal) = New AnonymousTypeOrDelegateTypeParameterSymbol(Me, ordinal)
Next
_typeParameters = typeParameters.AsImmutable()
End If
End Sub
Friend MustOverride Function GetAnonymousTypeKey() As AnonymousTypeKey
Public Overrides ReadOnly Property Name As String
Get
Return _nameAndIndex.Name
End Get
End Property
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Return _typeParameters.Length > 0
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property Layout As TypeLayout
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property MarshallingCharSet As CharSet
Get
Return DefaultMarshallingCharSet
End Get
End Property
Public MustOverride Overrides ReadOnly Property TypeKind As TypeKind
Public Overrides ReadOnly Property Arity As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property IsMustInherit As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotInheritable As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsComImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property CoClassType As TypeSymbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property DefaultPropertyName As String
Get
Return Nothing
End Get
End Property
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As DiagnosticBag) As NamedTypeSymbol
Return MakeAcyclicBaseType(diagnostics)
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return MakeAcyclicInterfaces(diagnostics)
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
' TODO - Perf
Return ImmutableArray.CreateRange(From member In GetMembers() Where CaseInsensitiveComparison.Equals(member.Name, name))
End Function
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
' TODO - Perf
Return New HashSet(Of String)(From member In GetMembers() Select member.Name)
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Me.Manager.ContainingModule.GlobalNamespace
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
' always global
Return Nothing
End Get
End Property
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Friend
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return True
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Friend Property NameAndIndex As NameAndIndex
Get
Return _nameAndIndex
End Get
Set(value As NameAndIndex)
Dim oldValue = Interlocked.CompareExchange(Me._nameAndIndex, value, Nothing)
Debug.Assert(oldValue Is Nothing OrElse
(oldValue.Name = value.Name AndAlso oldValue.Index = value.Index))
End Set
End Property
Friend MustOverride ReadOnly Property GeneratedNamePrefix As String
''' <summary> Describes the type descriptor location and property/parameter names associated with this location </summary>
Private NotInheritable Class LocationAndNames
Public ReadOnly Location As Location
Public ReadOnly Names As ImmutableArray(Of String)
Public Sub New(typeDescr As AnonymousTypeDescriptor)
Me.Location = typeDescr.Location
Me.Names = typeDescr.Fields.SelectAsArray(Function(d) d.Name)
End Sub
End Class
Public ReadOnly Property SmallestLocation As Location
Get
#If DEBUG Then
_locationAndNamesAreLocked = True
#End If
Return Me._adjustedPropertyNames.Location
End Get
End Property
''' <summary>
''' In emit phase every time a created anonymous type is referenced we try to adjust name of
''' template's fields as well as store the lowest location of the template. The last one will
''' be used for ordering templates and assigning emitted type names.
''' </summary>
Friend Sub AdjustMetadataNames(typeDescr As AnonymousTypeDescriptor)
' adjust template location only for type descriptors from source
Dim newLocation As Location = typeDescr.Location
Debug.Assert(newLocation.IsInSource)
Do
' Loop until we managed to set location and names OR we detected that we don't need
' to set it ('location' in type descriptor is bigger that the one in m_adjustedPropertyNames)
Dim currentAdjustedNames As LocationAndNames = Me._adjustedPropertyNames
If currentAdjustedNames IsNot Nothing AndAlso
Me.Manager.Compilation.CompareSourceLocations(currentAdjustedNames.Location, newLocation) <= 0 Then
' The template's adjusted property names do not need to be changed
Exit Sub
End If
#If DEBUG Then
Debug.Assert(Not _locationAndNamesAreLocked)
#End If
Dim newAdjustedNames As New LocationAndNames(typeDescr)
If Interlocked.CompareExchange(Me._adjustedPropertyNames, newAdjustedNames, currentAdjustedNames) Is currentAdjustedNames Then
' Changed successfully, proceed to updating the fields
Exit Do
End If
Loop
End Sub
Friend Function GetAdjustedName(index As Integer) As String
#If DEBUG Then
_locationAndNamesAreLocked = True
#End If
Dim names = Me._adjustedPropertyNames
Debug.Assert(names IsNot Nothing)
Debug.Assert(names.Names.Length > index)
Return names.Names(index)
End Function
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
Throw ExceptionUtilities.Unreachable
End Sub
Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol)
Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)()
End Function
End Class
End Class
End Namespace
|
panopticoncentral/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb
|
Visual Basic
|
mit
| 15,043
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.IO
Imports Bytescout.BarCodeReader
Module Module1
Sub Main()
Const imageFile As String = "USPSSackLabel.png"
Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(imageFile))
Dim reader As New Reader()
reader.RegistrationName = "demo"
reader.RegistrationKey = "demo"
' Set barcode type to find
reader.BarcodeTypesToFind.Interleaved2of5 = True ' "USPS Sack Label" barcode type is the same as "Interleaved 2 of 5"
' -----------------------------------------------------------------------
' NOTE: We can read barcodes from specific page to increase performance .
' For sample please refer to "Decoding barcodes from PDF by pages" program.
' -----------------------------------------------------------------------
' Read barcodes
Dim barcodes As FoundBarcode() = reader.ReadFrom(imageFile)
For Each barcode As FoundBarcode In barcodes
Console.WriteLine("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value)
Next
' Cleanup
reader.Dispose()
Console.WriteLine("Press any key to exit..")
Console.ReadKey()
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Decode usps sack label barcode with barcode reader sdk/Module1.vb
|
Visual Basic
|
apache-2.0
| 2,237
|
Imports IrrKlang
Module Module1
Sub Main()
' start up the engine
Dim engine As New ISoundEngine
' Now play some sound stream as music in 3d space, looped.
' We play it at position (0,0,0) in 3d space
Dim music As ISound = engine.Play3D("../../media/ophelia.mp3", 0, 0, 0, True)
' the following step isn't necessary, but to adjust the distance where
' the 3D sound can be heard, we set some nicer minimum distance
' (the default min distance is 1, for a small object). The minimum
' distance simply is the distance in which the sound gets played
' at maximum volume.
If Not (music Is Nothing) Then
music.MinDistance = 5.0F
End If
' Print some help text and start the display loop
Console.Out.Write(ControlChars.CrLf & "Playing streamed sound in 3D.")
Console.Out.WriteLine(ControlChars.CrLf & "Press ESCAPE to quit, any other key to play sound at random position." & ControlChars.CrLf)
Console.Out.WriteLine("+ = Listener position")
Console.Out.WriteLine("o = Playing sound")
Dim rand As Random = New Random
Dim radius As Single = 5
Dim posOnCircle As Single = 5
While (True) ' endless loop until user exits
' Each step we calculate the position of the 3D music.
' For this example, we let the
' music position rotate on a circle:
posOnCircle += 0.0399999991F
Dim pos3D As Vector3D = New Vector3D(radius * Math.Cos(posOnCircle), 0, _
radius * Math.Sin(posOnCircle * 0.5F))
' After we know the positions, we need to let irrKlang know about the
' listener position (always position (0,0,0), facing forward in this example)
' and let irrKlang know about our calculated 3D music position
engine.SetListenerPosition(0, 0, 0, 0, 0, 1)
If Not (music Is Nothing) Then
music.Position = pos3D
End If
' Now print the position of the sound in a nice way to the console
' and also print the play position
Dim stringForDisplay As String = " + "
Dim charpos As Integer = Math.Floor((CSng(pos3D.X + radius) / radius * 10.0F))
If (charpos >= 0 And charpos < 20) Then
stringForDisplay = stringForDisplay.Remove(charpos, 1)
stringForDisplay = stringForDisplay.Insert(charpos, "o")
End If
Dim playPos As Integer
If Not (music Is Nothing) Then
playPos = Integer.Parse(music.PlayPosition.ToString) ' how to convert UInt32 to Integer in visual basic?
End If
Dim output As String = ControlChars.Cr & String.Format("x:({0}) 3dpos: {1:f} {2:f} {3:f}, playpos:{4}:{5:00} ", _
stringForDisplay, pos3D.X, pos3D.Y, pos3D.Z, _
playPos \ 60000, (playPos Mod 60000) / 1000)
Console.Write(output)
System.Threading.Thread.Sleep(100)
' Handle user input: Every time the user presses a key in the console,
' play a random sound or exit the application if he pressed ESCAPE.
If _kbhit() <> 0 Then
Dim key As Integer = _getch()
If (key = 27) Then
Return ' user pressed ESCAPE key
Else
' Play random sound at some random position.
Dim pos As Vector3D = New Vector3D((rand.NextDouble() Mod radius * 2.0F) - radius, 0, 0)
Dim filename As String
If (rand.Next() Mod 2 <> 0) Then
filename = "../../media/bell.wav"
Else
filename = "../../media/explosion.wav"
End If
engine.Play3D(filename, pos.X, pos.Y, pos.Z)
Console.WriteLine(ControlChars.CrLf & "playing {0} at {1:f} {2:f} {3:f}", _
filename, pos.X, pos.Y, pos.Z)
End If
End If
End While
End Sub
' some simple function for reading keys from the console
<System.Runtime.InteropServices.DllImport("msvcrt")> _
Public Function _getch() As Integer
End Function
<System.Runtime.InteropServices.DllImport("msvcrt")> _
Public Function _kbhit() As Integer
End Function
End Module
|
redagito/CG2015
|
external/irrklang/irrKlang-1.5.0/examples.net/VisualBasic.02.3DSound/Module1.vb
|
Visual Basic
|
mit
| 4,519
|
' 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
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.Completion
Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data
Imports RoslynCompletion = Microsoft.CodeAnalysis.Completion
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public MustInherit Class AbstractVisualBasicCompletionProviderTests
Inherits AbstractCompletionProviderTests(Of VisualBasicTestWorkspaceFixture)
Protected Overrides Function CreateWorkspace(fileContents As String) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(fileContents, exportProvider:=ExportProvider)
End Function
Friend Overrides Function GetCompletionService(project As Project) As CompletionServiceWithProviders
Return Assert.IsType(Of VisualBasicCompletionService)(MyBase.GetCompletionService(project))
End Function
Private Protected Overrides Function BaseVerifyWorkerAsync(
code As String, position As Integer,
expectedItemOrNull As String, expectedDescriptionOrNull As String,
sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean,
checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?,
hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String,
isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task
Return MyBase.VerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
isComplexTextEdit, matchingFilters, flags)
End Function
Private Protected Overrides Async Function VerifyWorkerAsync(
code As String, position As Integer,
expectedItemOrNull As String, expectedDescriptionOrNull As String,
sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean,
checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?,
hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String,
isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task
' Script/interactive support removed for now.
' TODO: Re-enable these when interactive is back in the product.
If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then
Return
End If
Await VerifyAtPositionAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
isComplexTextEdit, matchingFilters, flags)
Await VerifyAtEndOfFileAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
isComplexTextEdit, matchingFilters, flags)
' Items cannot be partially written if we're checking for their absence,
' or if we're verifying that the list will show up (without specifying an actual item)
If Not checkForAbsence AndAlso expectedItemOrNull <> Nothing Then
Await VerifyAtPosition_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem,
displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters)
Await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem,
displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters)
End If
End Function
Protected Overrides Async Function VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit As String, position As Integer, itemToCommit As String, expectedCodeAfterCommit As String, sourceCodeKind As SourceCodeKind, Optional commitChar As Char? = Nothing) As Task
' Script/interactive support removed for now.
' TODO: Re-enable these when interactive is back in the product.
If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then
Return
End If
Await MyBase.VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind, commitChar)
End Function
Protected Overrides Function ItemPartiallyWritten(expectedItemOrNull As String) As String
If expectedItemOrNull(0) = "[" Then
Return expectedItemOrNull.Substring(1, 1)
End If
Return expectedItemOrNull.Substring(0, 1)
End Function
Protected Shared Function AddInsideMethod(text As String) As String
Return "Class C" & vbCrLf &
" Function F()" & vbCrLf &
" " & text & vbCrLf &
" End Function" & vbCrLf &
"End Class"
End Function
Protected Shared Function CreateContent(ParamArray contents As String()) As String
Return String.Join(vbCrLf, contents)
End Function
Protected Shared Function AddImportsStatement(importsStatement As String, text As String) As String
Return importsStatement & vbCrLf & vbCrLf & text
End Function
Protected Async Function VerifySendEnterThroughToEditorAsync(
initialMarkup As String, textTypedSoFar As String, expected As Boolean, Optional sourceCodeKind As SourceCodeKind = SourceCodeKind.Regular) As Task
Using workspace = TestWorkspace.CreateVisualBasic(initialMarkup, exportProvider:=ExportProvider)
Dim hostDocument = workspace.DocumentWithCursor
workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind)
Dim documentId = workspace.GetDocumentId(hostDocument)
Dim document = workspace.CurrentSolution.GetDocument(documentId)
Dim position = hostDocument.CursorPosition.Value
Dim service = GetCompletionService(document.Project)
Dim completionList = Await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke)
Dim item = completionList.Items.First(Function(i) i.DisplayText.StartsWith(textTypedSoFar))
Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(CompletionOptions.Default), item, textTypedSoFar))
End Using
End Function
Protected Sub TestCommonIsTextualTriggerCharacter()
Dim alwaysTriggerList =
{
"goo$$.",
"goo$$[",
"goo$$#",
"goo$$ ",
"goo$$="
}
For Each markup In alwaysTriggerList
VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=True)
Next
Dim triggerOnlyWithLettersList =
{
"$$a",
"$$_"
}
For Each markup In triggerOnlyWithLettersList
VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=False)
Next
Dim neverTriggerList =
{
"goo$$x",
"goo$$_"
}
For Each markup In neverTriggerList
VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=False, shouldTriggerWithTriggerOnLettersDisabled:=False)
Next
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.vb
|
Visual Basic
|
mit
| 9,193
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
<ExportLanguageService(GetType(ITypeInferenceService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicTypeInferenceService
Inherits AbstractTypeInferenceService(Of ExpressionSyntax)
Protected Overrides Function CreateTypeInferrer(semanticModel As SemanticModel, cancellationToken As CancellationToken) As AbstractTypeInferrer
Return New TypeInferrer(semanticModel, cancellationToken)
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Workspaces/VisualBasic/Portable/LanguageServices/VisualBasicTypeInferenceService.vb
|
Visual Basic
|
apache-2.0
| 998
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Organizing.Organizers
Friend Partial Class MemberDeclarationsOrganizer
Public Class Comparer
Implements IComparer(Of StatementSyntax)
' TODO(cyrusn): Allow users to specify the ordering they want
Public Enum OuterOrdering
Fields
EventFields
Constructors
Destructors
Properties
Events
Indexers
Operators
ConversionOperators
Methods
Types
Remaining
End Enum
Public Enum InnerOrdering
StaticInstance
Accessibility
Name
End Enum
Public Enum Accessibility
[Public]
[Protected]
[Friend]
[Private]
End Enum
Public Function Compare(x As StatementSyntax, y As StatementSyntax) As Integer Implements IComparer(Of StatementSyntax).Compare
If x Is y Then
Return 0
End If
Dim xOuterOrdering = GetOuterOrdering(x)
Dim yOuterOrdering = GetOuterOrdering(y)
Dim value = xOuterOrdering - yOuterOrdering
If value <> 0 Then
Return value
End If
If xOuterOrdering = OuterOrdering.Remaining Then
Return 1
ElseIf yOuterOrdering = OuterOrdering.Remaining Then
Return -1
End If
If xOuterOrdering = OuterOrdering.Fields OrElse yOuterOrdering = OuterOrdering.Fields Then
' Fields with initializers can't be reordered relative to
' themselves due to ordering issues.
Dim xHasInitializer = DirectCast(x, FieldDeclarationSyntax).Declarators.Any(Function(v) v.Initializer IsNot Nothing)
Dim yHasInitializer = DirectCast(y, FieldDeclarationSyntax).Declarators.Any(Function(v) v.Initializer IsNot Nothing)
If xHasInitializer AndAlso yHasInitializer Then
Return 0
End If
End If
Dim xIsShared = x.GetModifiers().Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
Dim yIsShared = y.GetModifiers().Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
value = Comparer(Of Boolean).Default.Inverse().Compare(xIsShared, yIsShared)
If value <> 0 Then
Return value
End If
Dim xAccessibility = GetAccessibility(x)
Dim yAccessibility = GetAccessibility(y)
value = xAccessibility - yAccessibility
If value <> 0 Then
Return value
End If
Dim xName = If(ShouldCompareByName(x), TryCast(x, DeclarationStatementSyntax).GetNameToken(), Nothing)
Dim yName = If(ShouldCompareByName(x), TryCast(y, DeclarationStatementSyntax).GetNameToken(), Nothing)
value = TokenComparer.NormalInstance.Compare(xName, yName)
If value <> 0 Then
Return value
End If
' Their names were the same. Order them by arity at this point.
Return x.GetArity() - y.GetArity()
End Function
Private Shared Function GetAccessibility(x As StatementSyntax) As Accessibility
Dim xModifiers = x.GetModifiers()
If xModifiers.Any(Function(t) t.Kind = SyntaxKind.PublicKeyword) Then
Return Accessibility.Public
ElseIf xModifiers.Any(Function(t) t.Kind = SyntaxKind.FriendKeyword) Then
Return Accessibility.Friend
ElseIf xModifiers.Any(Function(t) t.Kind = SyntaxKind.ProtectedKeyword) Then
Return Accessibility.Protected
Else
' Only fields are private in VB. All other members are public
If x.Kind = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
Else
Return Accessibility.Public
End If
End If
End Function
Private Function GetOuterOrdering(x As StatementSyntax) As OuterOrdering
Select Case x.Kind
Case SyntaxKind.FieldDeclaration
Return OuterOrdering.Fields
Case SyntaxKind.ConstructorBlock
Return OuterOrdering.Constructors
Case SyntaxKind.PropertyBlock
Return OuterOrdering.Properties
Case SyntaxKind.EventBlock
Return OuterOrdering.Events
Case SyntaxKind.OperatorBlock
Return OuterOrdering.Operators
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return OuterOrdering.Methods
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.StructureBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return OuterOrdering.Types
Case Else
Return OuterOrdering.Remaining
End Select
End Function
Private Shared Function ShouldCompareByName(x As StatementSyntax) As Boolean
' Constructors and operators should not be sorted by name.
Select Case x.Kind
Case SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock
Return False
Case Else
Return True
End Select
End Function
End Class
End Class
End Namespace
|
bbarry/roslyn
|
src/Features/VisualBasic/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.Comparer.vb
|
Visual Basic
|
apache-2.0
| 6,630
|
Imports System.ComponentModel
Imports System.IO
Imports System.Environment
'Lock Icons: http://creativecommons.org/licenses/by/3.0/
'Save and remove icons: http://creativecommons.org/licenses/by-nd/3.0/
'Source: https://www.iconfinder.com
'Status icons: http://www.icons-land.com
Public Class fm_main
Public block_status As Boolean
Public writehosts_back As String
Public hosts_path As String = "C:\Windows\System32\drivers\etc\hosts"
Dim appdatapath As String = GetFolderPath(SpecialFolder.ApplicationData) 'app data path
Dim fullapppath As String = appdatapath & "\Blockify" 'path where blockify will save files
Public sites_save_path As String = fullapppath & "\sites.bat" ' path for list of websites
Public hosts_bkup_save_path As String = fullapppath & "\hosts_bkup" 'path for hosts file backup
Dim sw As StreamWriter
Dim pw As String
Dim sites As String = ""
Dim edge() As Process ' dim browser processes
Dim chrome() As Process 'google chrome
Dim firefox() As Process 'firefox
Dim opera() As Process 'opera
Dim safari() As Process 'safari
Dim iexplore() As Process 'internet explorer
Dim browser_proc_names As New ArrayList 'list of browser process names for process killing
Private Sub hide_inputs() 'initial controls from form (password field, label and save button)
lbl_enterPw.Visible = False
btn_savePw.Visible = False
tb_savePw.Visible = False
End Sub
Private Sub show_inputs() 'show initial controls on form
lbl_enterPw.Visible = True
tb_savePw.Visible = True
btn_savePw.Visible = True
End Sub
Private Sub block_websites() 'perform block
Try
sw = New StreamWriter(hosts_path, True)
Dim sitetoblock As String = (Environment.NewLine & "127.0.0.1 " & sites) 'has to be www.google.com or google.com | NOT: http://www.google.com/
sw.Write(sitetoblock)
sw.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub get_running_browsers() 'browser process names for running check
chrome = Process.GetProcessesByName("chrome")
edge = Process.GetProcessesByName("MicrosoftEdge")
firefox = Process.GetProcessesByName("firefox")
opera = Process.GetProcessesByName("opera")
safari = Process.GetProcessesByName("Safari")
iexplore = Process.GetProcessesByName("iexplore")
End Sub
Private Sub browser_process_arraylist() ' browser process names added to arraylist
browser_proc_names.Add("chrome")
browser_proc_names.Add("MicrosoftEdge")
browser_proc_names.Add("firefox")
browser_proc_names.Add("opera")
browser_proc_names.Add("Safari")
browser_proc_names.Add("iexplore")
End Sub
Private objMutex As System.Threading.Mutex 'Mutex
Private Sub check_if_already_running()
'Check to prevent running twice
objMutex = New System.Threading.Mutex(False, "MyApplicationName")
If objMutex.WaitOne(0, False) = False Then
objMutex.Close()
objMutex = Nothing
MessageBox.Show("Another instance Is already running!")
End
End If
'If you get to this point it's first instance
End Sub
Private Sub fm_main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Height = 170
Try
check_if_already_running() 'check if app already running
block_status = False 'Set block bool to false
If My.Settings.Password = "" Then
MsgBox("Please enter a password")
Me.Height = 250
btn_block.Enabled = False
btn_unblock.Enabled = False
MainMenuStrip.Items.Item(0).Enabled = False 'disable actions toolstrip
show_inputs()
tb_savePw.Focus()
End If
'check if a list of websites exist
If File.Exists(sites_save_path) Then
Dim blocked_websites As String
Using reader As StreamReader = New StreamReader(sites_save_path)
blocked_websites = reader.ReadToEnd
End Using
tb_blockedSites.Text = blocked_websites
Else
tb_blockedSites.Text = "No websites are currently being blocked."
End If
'TODO Update about me.
If Directory.Exists(fullapppath) = False Then
Directory.CreateDirectory(appdatapath & "\Blockify")
End If
If File.Exists(fullapppath & "\hosts_bkup") = False Then
File.Copy(hosts_path, fullapppath & "\hosts_bkup", True)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub fm_main_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
If My.Settings.Password <> "" Then
fm_enterpw_closing.Show()
e.Cancel = True 'cancel form closing. form called fm_enterpw_closing will be responsible for closing application
End If
End Sub
Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
Dim i As Integer
i = TabControl1.SelectedIndex
If i = 1 Then
Height = 250
ElseIf My.Settings.Password = "" Then
Height = 250
Else
Height = 170
End If
End Sub
Private Sub BlockSitesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BlockSitesToolStripMenuItem.Click
fm_enterPw.Show()
End Sub
Private Sub btn_savePw_Click(sender As Object, e As EventArgs) Handles btn_savePw.Click
Try
pw = tb_savePw.Text
My.Settings.Password = pw
My.Settings.Save()
MsgBox("Password Saved!", vbInformation, "")
Me.Height = 165
hide_inputs()
btn_block.Enabled = True
btn_unblock.Enabled = True
MainMenuStrip.Items.Item(0).Enabled = True 'enable actions toolstrip
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btn_block_Click(sender As Object, e As EventArgs) Handles btn_block.Click
Try
get_running_browsers() 'check if browsers opened
If edge.Count > 0 Or chrome.Count > 0 Or firefox.Count > 0 Or opera.Count > 0 Or safari.Count > 0 Or iexplore.Count > 0 Then
If MessageBox.Show("You currently have a web browser opened. Click ""Yes"" if you would Like this program to automatically close it/them AFTER you have saved your work. ", "Opened Web Browser Detected", MessageBoxButtons.YesNo) = DialogResult.Yes Then
browser_process_arraylist()
Dim i As Integer
For i = 0 To browser_proc_names.Count - 1 'loop through array list
Dim proc_name As String = browser_proc_names(i).ToString
For Each p As Process In Process.GetProcessesByName(proc_name) 'kill processes of browsers within arraylist
p.Kill() 'kill process
Next
Next
GoTo continueblocking
Else
MessageBox.Show("Please try clicking the block button again after you have saved your work and closed all browsers.", "Opened Web Browser Detected")
End If
Else
continueblocking:
If block_status = False Then
If File.Exists(sites_save_path) Then 'check for the sites to block
Dim Numofwebsites As Integer = File.ReadAllLines(sites_save_path).Length
Dim sr As New StreamReader(sites_save_path)
Do Until sr.Peek = -1
sites = sr.ReadLine()
block_websites() 'Block the websites
Loop
sr.Close() 'close the stream reader
MessageBox.Show("Block Activated.")
pb_status.Image = My.Resources.Circle_Green
lbl_status.Text = "Blocking" & " " & Numofwebsites & " " & "websites."
lbl_status.Visible = True
block_status = True
Else
MsgBox("Please enter websites to block", vbInformation, "Block Websites")
fm_blockSites.Show()
End If
Else
MsgBox("Websites already being blocked.")
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub BlockedWebsitesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BlockedWebsitesToolStripMenuItem.Click
fm_change_pw.Show()
End Sub
Private Sub btn_unblock_Click(sender As Object, e As EventArgs) Handles btn_unblock.Click
Try
If block_status = True Then
fm_enterPw_unblock.Show()
Else
MsgBox("No websites are currently being blocked.", vbInformation, "")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
fm_about.Show()
End Sub
Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
If File.Exists(sites_save_path) Then
fm_enterpw_editblocked_websites_list.Show()
Else
MsgBox("No websites are currently being blocked. Please block a website first", vbInformation, "")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
My.Settings.Password = ""
End Sub
Private Sub tb_savePw_TextChanged(sender As Object, e As EventArgs) Handles tb_savePw.TextChanged
btn_savePw.Enabled = True
End Sub
Private Sub tb_savePw_KeyDown(sender As Object, e As KeyEventArgs) Handles tb_savePw.KeyDown
If e.KeyCode = Keys.Enter Then
btn_savePw.PerformClick()
End If
End Sub
End Class
|
UVLabs/Blockify
|
Blockify/fm_main.vb
|
Visual Basic
|
mit
| 10,547
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FindReplace
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.TXTsearch = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.BTNnext = New System.Windows.Forms.Button()
Me.BTNcancel = New System.Windows.Forms.Button()
Me.CHKcase = New System.Windows.Forms.CheckBox()
Me.BTNprev = New System.Windows.Forms.Button()
Me.TXTreplace = New System.Windows.Forms.TextBox()
Me.Button1 = New System.Windows.Forms.Button()
Me.Label2 = New System.Windows.Forms.Label()
Me.BTNreplaceAll = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'TXTsearch
'
Me.TXTsearch.Location = New System.Drawing.Point(88, 11)
Me.TXTsearch.Name = "TXTsearch"
Me.TXTsearch.Size = New System.Drawing.Size(153, 20)
Me.TXTsearch.TabIndex = 3
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(12, 14)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(56, 13)
Me.Label1.TabIndex = 1
Me.Label1.Text = "Find what:"
'
'BTNnext
'
Me.BTNnext.Location = New System.Drawing.Point(256, 38)
Me.BTNnext.Name = "BTNnext"
Me.BTNnext.Size = New System.Drawing.Size(79, 23)
Me.BTNnext.TabIndex = 1
Me.BTNnext.Text = "Find Next"
Me.BTNnext.UseVisualStyleBackColor = True
'
'BTNcancel
'
Me.BTNcancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.BTNcancel.Location = New System.Drawing.Point(256, 125)
Me.BTNcancel.Name = "BTNcancel"
Me.BTNcancel.Size = New System.Drawing.Size(79, 23)
Me.BTNcancel.TabIndex = 2
Me.BTNcancel.Text = "Cancel"
Me.BTNcancel.UseVisualStyleBackColor = True
'
'CHKcase
'
Me.CHKcase.AutoSize = True
Me.CHKcase.Location = New System.Drawing.Point(12, 84)
Me.CHKcase.Name = "CHKcase"
Me.CHKcase.Size = New System.Drawing.Size(94, 17)
Me.CHKcase.TabIndex = 4
Me.CHKcase.Text = "Case sensitive"
Me.CHKcase.UseVisualStyleBackColor = True
'
'BTNprev
'
Me.BTNprev.Location = New System.Drawing.Point(256, 9)
Me.BTNprev.Name = "BTNprev"
Me.BTNprev.Size = New System.Drawing.Size(79, 23)
Me.BTNprev.TabIndex = 4
Me.BTNprev.Text = "Find Previous"
Me.BTNprev.UseVisualStyleBackColor = True
'
'TXTreplace
'
Me.TXTreplace.Location = New System.Drawing.Point(88, 40)
Me.TXTreplace.Name = "TXTreplace"
Me.TXTreplace.Size = New System.Drawing.Size(153, 20)
Me.TXTreplace.TabIndex = 6
'
'Button1
'
Me.Button1.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Button1.Location = New System.Drawing.Point(256, 67)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(79, 23)
Me.Button1.TabIndex = 8
Me.Button1.Text = "Replace"
Me.Button1.UseVisualStyleBackColor = True
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(12, 43)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(72, 13)
Me.Label2.TabIndex = 9
Me.Label2.Text = "Replace with:"
'
'BTNreplaceAll
'
Me.BTNreplaceAll.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.BTNreplaceAll.Location = New System.Drawing.Point(256, 96)
Me.BTNreplaceAll.Name = "BTNreplaceAll"
Me.BTNreplaceAll.Size = New System.Drawing.Size(79, 23)
Me.BTNreplaceAll.TabIndex = 10
Me.BTNreplaceAll.Text = "Replace All"
Me.BTNreplaceAll.UseVisualStyleBackColor = True
'
'FindReplace
'
Me.AcceptButton = Me.BTNnext
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.CancelButton = Me.BTNcancel
Me.ClientSize = New System.Drawing.Size(347, 159)
Me.Controls.Add(Me.BTNreplaceAll)
Me.Controls.Add(Me.TXTreplace)
Me.Controls.Add(Me.TXTsearch)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.BTNprev)
Me.Controls.Add(Me.CHKcase)
Me.Controls.Add(Me.BTNcancel)
Me.Controls.Add(Me.BTNnext)
Me.Controls.Add(Me.Label1)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "FindReplace"
Me.ShowIcon = False
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Find"
Me.TopMost = True
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents TXTsearch As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents BTNnext As System.Windows.Forms.Button
Friend WithEvents BTNcancel As System.Windows.Forms.Button
Friend WithEvents CHKcase As System.Windows.Forms.CheckBox
Friend WithEvents BTNprev As System.Windows.Forms.Button
Friend WithEvents TXTreplace As System.Windows.Forms.TextBox
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents BTNreplaceAll As System.Windows.Forms.Button
End Class
|
gumgl/VB.NET
|
NotePad--/FindReplace.Designer.vb
|
Visual Basic
|
mit
| 6,540
|
Imports Transporter_AEHF.Objects.Enumerations
<Serializable()> Public Class PositionerObject
Private _positionerType As Enumerations.PositionerModel
Private _connectionString As String = ""
Private _comPortNumber As Integer = 0
Private _interleaveStep As Double = 30
Private _azimuthStep As Double = 1
Private _lastAzimuth As Double = 0
Private _azimuthArray() As Double
Private _totalRevolutions As Integer = 0
Private _preventCableWrap As Boolean = False
Private _ignoreElevationParameters As Boolean = False
Private _elevationInterleaveStep As Double = 30
Private _elevationStep As Double = 1
Private _azimuthStart As Double = 0
Private _azimuthStop As Double = 360
Private _elevationStart As Double = 0
Private _elevationStop As Double = 0
Private _elevationArray() As Double
Private _lastElevation As Double = 0
Property GetPositionerType() As Enumerations.PositionerModel
Get
Return _positionerType
End Get
Set(ByVal value As Enumerations.PositionerModel)
_positionerType = Value
End Set
End Property
Property GetConnectionString() As String
Get
Return _connectionString
End Get
Set(ByVal value As String)
_connectionString = Value
End Set
End Property
Property GetComPortNumber() As Integer
Get
Return _comPortNumber
End Get
Set(ByVal value As Integer)
_comPortNumber = Value
End Set
End Property
Property GetInterleaveStep() As Double
Get
Return _interleaveStep
End Get
Set(ByVal value As Double)
_interleaveStep = Value
End Set
End Property
Property GetAzimuthStep() As Double
Get
Return _azimuthStep
End Get
Set(ByVal value As Double)
_azimuthStep = Value
End Set
End Property
Property GetLastAzimuth() As Double
Get
Return _lastAzimuth
End Get
Set(ByVal value As Double)
_lastAzimuth = Value
End Set
End Property
Property GetAzimuthArray() As Double()
Get
Return _azimuthArray
End Get
Set(ByVal value As Double())
_azimuthArray = Value
End Set
End Property
Property GetTotalRevolutions() As Integer
Get
Return _totalRevolutions
End Get
Set(ByVal value As Integer)
_totalRevolutions = Value
End Set
End Property
Property GetPreventCableWrap() As Boolean
Get
Return _preventCableWrap
End Get
Set(ByVal value As Boolean)
_preventCableWrap = Value
End Set
End Property
Property GetIgnoreElevationParameters() As Boolean
Get
Return _ignoreElevationParameters
End Get
Set(ByVal value As Boolean)
_ignoreElevationParameters = Value
End Set
End Property
Property GetElevationInterleaveStep() As Double
Get
Return _elevationInterleaveStep
End Get
Set(ByVal value As Double)
_elevationInterleaveStep = Value
End Set
End Property
Property GetElevationStep() As Double
Get
Return _elevationStep
End Get
Set(ByVal value As Double)
_elevationStep = Value
End Set
End Property
Property GetAzimuthStart() As Double
Get
Return _azimuthStart
End Get
Set(ByVal value As Double)
_azimuthStart = Value
End Set
End Property
Property GetAzimuthStop() As Double
Get
Return _azimuthStop
End Get
Set(ByVal value As Double)
_azimuthStop = Value
End Set
End Property
Property GetElevationStart() As Double
Get
Return _elevationStart
End Get
Set(ByVal value As Double)
_elevationStart = Value
End Set
End Property
Property GetElevationStop() As Double
Get
Return _elevationStop
End Get
Set(ByVal value As Double)
_elevationStop = Value
End Set
End Property
Property GetElevationArray() As Double()
Get
Return _elevationArray
End Get
Set(ByVal value As Double())
_elevationArray = Value
End Set
End Property
Property GetlastElevation() As Double
Get
Return _lastElevation
End Get
Set(ByVal value As Double)
_lastElevation = Value
End Set
End Property
End Class
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Objects/PositionerObject.vb
|
Visual Basic
|
mit
| 4,789
|
' This has to be here in order to replay old trace files. It's a namespace confliction otherwise
Public Class Enumerations
#Region "Oscope Parameters"
Public Enum MathOperators
FftMagnitude
Max
Min
AbsoluteValue
Average
Square
SquareRoot
End Enum
Public Enum Source
Channel1
Channel2
Channel3
Channel4
Function1
Function2
Function3
Function4
Constant
End Enum
#End Region
#Region "Analyzer Parameters"
Public Enum Coupling
Dc
Ac
End Enum
Public Enum TraceDetectorType
Peak
Average
Sample
Normal
NegativePeak
End Enum
Public Enum TraceTypes
ClearWrite
MaxHold
MinHold
TraceAverage
End Enum
Public Enum AnalyzerModels
Agilent9030APxa26 = 0
Agilent9030APxa50 = 1
Agilent4407 = 2
Agilent4448APsa = 3
AgilentFieldFox = 4
Agilent9020AMxa26 = 5
End Enum
Public Enum PreAmpstate
Isoff
IsOn
End Enum
Public Enum AnalyzerAssignments
Analyzer0
Analyzer1
Analyzer2
Analyzer3
Analyzer4
Analyzer5
Analyzer6
Analyzer7
Analyzer8
Analyzer9
End Enum
Public Enum AnalyzerMarkerMode
Position
Delta
Fixed
Off
End Enum
#End Region
#Region "Positioners"
Public Enum PositionerModel
Burchfield
DirectedPerception
End Enum
Public Enum PositionerAssignments
Positioner0
Positioner1
Positioner2
Positioner3
Positioner4
Positioner5
Positioner6
Positioner7
Positioner8
Positioner9
End Enum
''' <summary>
''' Speed Mode is either Independent or Velocity
''' </summary>
''' <remarks></remarks>
Public Enum SpeedMode
''' <summary>In independant mode, a value given to pan speed will set the speed</summary>
Independent
''' <summary>In velocity mode, a value given to pan speed will move the positioner at that speed</summary>
Velocity
End Enum
''' <summary>
''' Command mode is either Immediate or Slaved
''' </summary>
''' <remarks></remarks>
Public Enum CommandMode
''' <summary>Immediate allows the positioner to move as soon as command is issued</summary>
Immediate
''' <summary>Slaved mode means the positioner will not move until await command is issued</summary>
Slaved
End Enum
''' <summary>
''' Pan Rotation Direction. Left is counterclockwise while looking down on unit from above.
''' </summary>
''' <remarks></remarks>
Public Enum PanRotationDirection
''' <summary>Counterclockwise</summary>
Left
''' <summary>Clockwise</summary>
Right
End Enum
''' <summary>
''' Tilt Rotation Direction. Forward or Backward
''' </summary>
''' <remarks></remarks>
Public Enum TiltRotationDirection
''' <summary>Positive</summary>
Forward
''' <summary>Negative</summary>
Backward
End Enum
Public Enum StepMode
Full
Half
Quarter
Eighth
Auto
End Enum
Public Enum PidValue
Pid1
Pid2
Pid4
Pid8
End Enum
#End Region
#Region "GPS Sources"
Public Enum GpsSources
GarminGpsMapSeries
XlGps
End Enum
#End Region
#Region "Antenna Parameters"
Public Enum Polarizations
Vertical
Horizontal
RightHandCircular
LeftHandCircular
End Enum
Public Enum AntennaTypes
MonoPole
DiPole
LogPeriodic
StandardGainHorn
DualRidgedWaveguideHorn
Dish
Yagi
LogSpiral
Discone
PhasedArray
End Enum
#End Region
#Region "Connectors"
Public Enum ConnectorType
NFemale
NMale
BncMale
BncFemale
SmaMale
TncMale
K_2P92MmMale
Apc_3P5MmMale
Apc_2P4MmMale
SmaFemale
TncFemale
K_2P92MmFemale
Apc_3P5MmFemale
Pc_2P4MmFemale
End Enum
#End Region
#Region "Survey/Project Specific Paramters"
Public Enum MissionType
Transporter
Survey
End Enum
Public Enum MiliSecdelayValues
Ten = 10
Fifty = 50
OneHundred = 100
TwoHundred = 200
ThreeHundred = 300
FourHundred = 400
FiveHundred = 500
EightHundred = 800
OneThousand = 1000
FifteenHundred = 1500
TwoThousand = 2000
ThreeThousand = 3000
End Enum
#End Region
#Region "Connections"
Public Enum ConnectionType
Com
Gpib
Ip
Usb
End Enum
#End Region
#Region "Switches and Switch Drivers"
Public Enum SwitchDriverTypes
Adam6060
Burchfield
KeysightPxi
End Enum
Public Enum SwitchTypes
Agilent87106D
RadiallRSeries
End Enum
'Public Enum CaoxialSwitchTypes
' AGILENT_87106D
' RADIALL_R_series
'End Enum
Public Enum Adam6060DriveLines
_0
_1
_2
_3
_4
_5
End Enum
Public Enum SwitchPathAliases
DontCare
End Enum
#End Region
#Region "Future Main Enums"
Public Enum SessionType
Survey
Replay
Coverage
Hazard
End Enum
#End Region
#Region "Logger"
Public Enum LoggerType
Verbose
Debug
Off
End Enum
#End Region
#Region "EMC"
#Region "MATH"
Enum Operatortype
Add
SubTract
Multiply
Divide
ToThePower
Log10
End Enum
#End Region
#Region "RfType"
Public Enum FrequencySuffix
AutoFormat = -1 'tell function to select units
Hertz = 0 'the values here are also used as exponents for converting values
Hz = 0
KHz = 3
MHz = 6
GHz = 9
THz = 12
End Enum ' Frequency Suffixes
#End Region
#Region "Distance"
Public Enum DistanceUnit ' this enum is part of the class where it is used
Meter
CentiMeter
MiliMeter
KiloMeter
StatuteMile
NauticalMile
Feet
Yard
Inch
End Enum
#End Region
#Region "Power"
Public Enum PowerUnits
MicroWatt = -6
MilliWatt = -3
Watt = 0
KiloWatt = 3
MegaWatt = 6
GigaWatt = 9
TeraWatt = 12
DBm
DBw
End Enum
#End Region
#Region "Gain"
Public Enum GainUnit
DB
Numeric
End Enum
#End Region
#End Region
#Region "Misc"
Public Enum Impedance
I50
I75
I300
I377
End Enum
Public Enum Types
Antenna
LowNoiseAmplifier
PowerAmplifier
Filter
Attenuator
Splitter
PhaseShifter
Cable
Adapter
WaveGuide
Probe
BiasTee
End Enum
Public Enum Errc
Nf3
Xb3
Nf4
Xd2
Nd
End Enum
#End Region
End Class
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Objects/Enumerations/enumerations2.vb
|
Visual Basic
|
mit
| 8,534
|
'------------------------------------------------------------------------------
' <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 ReporteListaretencionesCuarta
'''<summary>
'''Control Head1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
'''<summary>
'''Control form1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''Control ReportViewer1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ReportViewer1 As Global.Telerik.ReportViewer.WebForms.ReportViewer
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/ReporteListaRetencionesCuarta.aspx.designer.vb
|
Visual Basic
|
mit
| 1,522
|
Namespace GridWebBasics
Public Class PrintGridWeb
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' If first visit this page clear GridWeb1 and load data
If Not IsPostBack AndAlso Not GridWeb1.IsPostBack Then
GridWeb1.WorkSheets.Clear()
GridWeb1.WorkSheets.Add()
LoadData()
End If
End Sub
Private Sub LoadData()
' License li = new License();
' li.SetLicense(@"D:\grid_project\ZZZZZZ_release_version\Aspose.Total.20141214.lic");
' Gets the web application's path.
Dim path As String = TryCast(Me.Master, Site).GetDataDir()
Dim fileName As String = path + "\GridWebBasics\SampleData.xls"
' Imports from an excel file.
GridWeb1.ImportExcelFile(fileName)
End Sub
Protected Sub GridWeb1_SaveCommand(sender As Object, e As EventArgs)
' Generates a temporary file name.
Dim filename As String = Session.SessionID + "_out.xls"
Dim path As String = TryCast(Me.Master, Site).GetDataDir() + "\GridWebBasics\"
' Saves to the file.
Me.GridWeb1.SaveToExcelFile(path + filename)
' Sents the file to browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment; filename=" + filename)
Response.WriteFile(path + filename)
Response.End()
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples.GridWeb/VisualBasic/GridWebBasics/PrintGridWeb.aspx.vb
|
Visual Basic
|
mit
| 1,624
|
Imports Hermes.Cryptography
Imports Hermes.Email
Imports Leviathan.Visualisation
Imports System.Net.Mail
Imports IT = Leviathan.Visualisation.InformationType
Namespace Commands
Partial Public Class CommandEmailOutput
Implements ICommandsOutput
Implements ICommandsOutputWriter
#Region " Private Constants "
Private Shared HTML_SPACE As String = " "
#End Region
#Region " Protected Constants "
Protected Shared COLOUR_BACKGROUND As String = "#000000"
Protected Shared COLOUR_GENERAL As String = "#DDDDDD"
Protected Shared COLOUR_PERFORMANCE As String = "#808000"
Protected Shared COLOUR_SUCCESS As String = "#00FF00"
Protected Shared COLOUR_INFORMATION As String = "#0000FF"
Protected Shared COLOUR_WARNING As String = "#FFFF00"
Protected Shared COLOUR_ERROR As String = "#FF0000"
Protected Shared COLOUR_DEBUG As String = "#808080"
Protected Shared COLOUR_LOG As String = "#808080"
Protected Shared COLOUR_QUESTION As String = "#FFFFFF"
#End Region
#Region " Private Properties "
Private ReadOnly Property Font_Size As Integer
Get
If CharacterWidth >= 300 Then
Return 10
ElseIf CharacterWidth >= 250 Then
Return 11
ElseIf CharacterWidth >= 200 Then
Return 12
Else
Return 13
End If
End Get
End Property
#End Region
#Region " Private Methods "
Private Sub Write_HtmlStart()
Email_Message.AppendLine("<html>")
Email_Message.AppendLine(String.Format("<body lang='EN-GB' style='background-color: {0}'>", COLOUR_BACKGROUND))
Email_Message.AppendLine(String.Format("<div style='FONT-FAMILY: Lucida Console, Courier New, Courier; COLOR: #000000; FONT-SIZE: {0}px'>", Font_Size))
End Sub
Private Sub Write_HtmlEnd()
Email_Message.AppendLine("</div>")
Email_Message.AppendLine("</body>")
Email_Message.AppendLine("</html>")
End Sub
#End Region
#Region " ICommandsOutput Implementation "
Private Sub Write_Outputs( _
ParamArray ByVal values As IFixedWidthWriteable() _
) Implements ICommandsOutput.Show_Outputs
If Not values Is Nothing Then
For i As Integer = 0 To values.Count - 1
If HasWritten OrElse i > 0 Then
TerminateLine()
ElseIf UseHtml Then
Write_HtmlStart()
End If
HasWritten = True
values(i).Write(CharacterWidth, Me, 0)
Next
End If
End Sub
Private Sub Write_Close() Implements ICommandsOutput.Close
If Email_Message.BodyLength > 0 Then
' -- Terminate the HTML if required --
If UseHtml Then
Write_HtmlEnd()
Email_Message.Body_Format = BodyType.Html
End If
' -- Set the Message Subject --
Email_Message.Subject = Subject
' -- Set Up the Hermes Recipient List --
Dim _distribution As New Distribution
_distribution.Sending_Format = SendingType.Single_Recipient
_distribution.Add(ToAddresses)
' -- Set the From/Reply-To --
Dim _from As System.Net.Mail.MailAddress
If Not String.IsNullOrEmpty(FromAddress) Then
_from = Hermes.Email.Manager.CreateAddress(FromAddress, FromDisplay)
Else
_from = Hermes.Email.Manager.CreateAddress(Cipher.Create_Password(12, 0).ToLower() & _
Default_From_Domain, "Leviathan")
End If
Dim _replyTo As System.Net.Mail.MailAddress = Nothing
If Not String.IsNullOrEmpty(ReplyToAddress) Then _replyTo = _
Hermes.Email.Manager.CreateAddress(ReplyToAddress, ReplyToDisplay)
' -- Set Up the Hermes Manager and Send Email --
Dim _manager = new Hermes.Email.Manager()
_manager.Suppress_Send = Suppress
_manager.SMTP_MaxBatch = 20
_manager.Client_Application = "Leviathan"
If Not Log Is Nothing Then _manager.Logging_Directory = Log
_manager.SMTP_Server = Hermes.Email.Manager.CreateServer(Server)
_manager.SMTP_Port = ServerPort
_manager.Use_SSL = ServerSSL
_manager.Verify_SSL = ServerValidateCertificate
If String.IsNullOrEmpty(ServerUsername) Then
_manager.SMTP_Credential = Hermes.Email.Manager.CreateIntegratedCredential()
Else
_manager.SMTP_Credential = Hermes.Email.Manager.CreateCredential(ServerUsername, ServerPassword, ServerDomain)
End If
' -- Send Email --
If _replyTo Is Nothing Then
_manager.SendMessage(_from, _Distribution, Email_Message, Nothing, "Command Email Output")
Else
_manager.SendMessage(_from, _Distribution, Email_Message, Nothing, "Command Email Output", _replyTo)
End If
End If
End Sub
#End Region
#Region " ICommandsOutputWriter Implementation "
Private Sub Write( _
ByVal value As String, _
ByVal type As InformationType _
) _
Implements ICommandsOutputWriter.Write
If Not String.IsNullOrEmpty(value) Then
If UseHtml Then
Select Case type
Case IT.General
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_GENERAL, value)
Case IT.Debug
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_DEBUG, value)
Case IT.Log
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_LOG, value)
Case IT.[Error]
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_ERROR, value)
Case IT.Information
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_INFORMATION, value)
Case IT.Performance
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_PERFORMANCE, value)
Case IT.Success
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_SUCCESS, value)
Case IT.Warning
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_WARNING, value)
Case IT.Question
Email_Message.AppendFormat("<font color='{0}'>{1}</font>", COLOUR_QUESTION, value)
Case Else
Email_Message.Append(value)
End Select
Else
Email_Message.Append(value)
End If
End If
End Sub
Private Function FixedWidthWrite( _
ByRef value As String, _
ByVal width As Integer, _
ByVal type as InformationType _
) As Boolean _
Implements ICommandsOutputWriter.FixedWidthWrite
Dim returnValue As Boolean
Dim lengthWritten As Integer
If Not String.IsNullOrEmpty(value) Then _
Write(CubeControl.MaxWidthWrite(value, width, lengthWritten, returnValue), type)
' Write the Padding Spaces
If UseHtml Then
For i As Integer = 0 To (width - lengthWritten) - 1
Write(HTML_SPACE, InformationType.None)
Next
Else
Write(New String(SPACE, width - lengthWritten), InformationType.None)
End If
Return returnValue
End Function
Private Sub TerminateLine( _
Optional numberOfTimes As System.Int32 = 1 _
) _
Implements ICommandsOutputWriter.TerminateLine
For i As Integer = 1 To numberOfTimes
If UseHtml Then
Email_Message.AppendLine("<br />")
Else
Email_Message.AppendLine()
End If
Next
End Sub
#End Region
End Class
End Namespace
|
thiscouldbejd/Leviathan
|
_Commands/Partials/CommandEmailOutput.vb
|
Visual Basic
|
mit
| 7,118
|
#Region "Microsoft.VisualBasic::68bf95ebc790eed59438e12c8239f4c9, src\mzkit\mzkit\pages\dockWindow\frmStartPage.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 frmStartPage
'
' Sub: frmStartPage_Load
'
' /********************************************************************************/
#End Region
Public Class frmStartPage
Dim startPage As New PageStart
Private Sub frmStartPage_Load(sender As Object, e As EventArgs) Handles Me.Load
Controls.Add(startPage)
startPage.Dock = DockStyle.Fill
Me.Icon = My.Resources.chemistry
Me.ShowIcon = True
' Me.ShowInTaskbar = True
SaveDocumentToolStripMenuItem.Enabled = False
CopyFullPathToolStripMenuItem.Enabled = False
OpenContainingFolderToolStripMenuItem.Enabled = False
End Sub
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/mzkit/mzkit/pages/dockWindow/frmStartPage.vb
|
Visual Basic
|
mit
| 2,265
|
Imports StaxRip.UI
Imports System.ComponentModel
Public Class CommandLineControl
Inherits UserControl
#Region "Designer"
Friend WithEvents tb As TextBoxEx
Friend WithEvents tlpMain As System.Windows.Forms.TableLayoutPanel
Friend WithEvents bu As StaxRip.UI.ButtonEx
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Private components As System.ComponentModel.IContainer
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.tb = New StaxRip.UI.TextBoxEx()
Me.bu = New StaxRip.UI.ButtonEx()
Me.tlpMain = New System.Windows.Forms.TableLayoutPanel()
Me.tlpMain.SuspendLayout()
Me.SuspendLayout()
'
'tb
'
Me.tb.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.tb.Location = New System.Drawing.Point(0, 0)
Me.tb.Margin = New System.Windows.Forms.Padding(0)
Me.tb.Multiline = True
Me.tb.Size = New System.Drawing.Size(235, 205)
'
'bu
'
Me.bu.Anchor = System.Windows.Forms.AnchorStyles.Top
Me.bu.Location = New System.Drawing.Point(245, 0)
Me.bu.Margin = New System.Windows.Forms.Padding(10, 0, 0, 0)
Me.bu.ShowMenuSymbol = True
Me.bu.Size = New System.Drawing.Size(70, 70)
'
'tlpMain
'
Me.tlpMain.ColumnCount = 2
Me.tlpMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.tlpMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
Me.tlpMain.Controls.Add(Me.bu, 1, 0)
Me.tlpMain.Controls.Add(Me.tb, 0, 0)
Me.tlpMain.Dock = System.Windows.Forms.DockStyle.Fill
Me.tlpMain.Location = New System.Drawing.Point(0, 0)
Me.tlpMain.Margin = New System.Windows.Forms.Padding(0)
Me.tlpMain.Name = "tlpMain"
Me.tlpMain.RowCount = 1
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.tlpMain.Size = New System.Drawing.Size(315, 205)
Me.tlpMain.TabIndex = 2
'
'CommandLineControl
'
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit
Me.Controls.Add(Me.tlpMain)
Me.Margin = New System.Windows.Forms.Padding(0)
Me.Name = "CommandLineControl"
Me.Size = New System.Drawing.Size(315, 205)
Me.tlpMain.ResumeLayout(False)
Me.tlpMain.PerformLayout()
Me.ResumeLayout(False)
End Sub
#End Region
<Browsable(False),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Property RestoreFunc As Func(Of String)
Private HelpFileValue As String
Private cms As ContextMenuStripEx
Event PresetsChanged(presets As String)
Event ValueChanged(value As String)
Sub New()
InitializeComponent()
components = New System.ComponentModel.Container
AddHandler tb.TextChanged, Sub() RaiseEvent ValueChanged(tb.Text)
End Sub
<Browsable(False),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Property Presets As String
Sub MenuItenClick(value As String)
Dim tup = Macro.ExpandGUI(value)
If tup.Cancel Then Exit Sub
value = tup.Value
If Not value Like "*$*$*" Then
If tb.Text = "" Then
tb.Text = value
Else
tb.Text = tb.Text.Trim + " " + value
End If
End If
End Sub
Sub EditPresets()
Using dia As New MacroEditorDialog
dia.SetMacroDefaults()
dia.MacroEditorControl.Value = Presets.FormatColumn("=")
dia.Text = "Menu Editor"
If Not RestoreFunc Is Nothing Then
dia.bnContext.Text = " Restore Defaults... "
dia.bnContext.Visible = True
dia.bnContext.AddClickAction(Sub() If MsgOK("Restore defaults?") Then dia.MacroEditorControl.Value = RestoreFunc.Invoke)
dia.MacroEditorControl.rtbDefaults.Text = RestoreFunc.Invoke
End If
If dia.ShowDialog(FindForm) = DialogResult.OK Then
Presets = dia.MacroEditorControl.Value.ReplaceUnicode
RaiseEvent PresetsChanged(Presets)
End If
End Using
End Sub
Private Sub bCmdlAddition_Click() Handles bu.Click
Dim cms = TextCustomMenu.GetMenu(Presets, bu, components, AddressOf MenuItenClick)
Me.components.Add(cms)
cms.Items.Add(New ToolStripSeparator)
cms.Items.Add(New ActionMenuItem("Edit Menu...", AddressOf EditPresets))
cms.Show(bu, 0, bu.Height)
End Sub
Private Sub CmdlControl_Layout(sender As Object, e As LayoutEventArgs) Handles Me.Layout
tb.Height = Height
End Sub
Private Sub CommandLineControl_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not DesignHelp.IsDesignMode Then Font = New Font("Consolas", 10 * s.UIScaleFactor)
End Sub
End Class
|
stax76/staxrip
|
Controls/CommandLineControl.vb
|
Visual Basic
|
mit
| 5,532
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CSharp
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.Options
Imports Microsoft.CodeAnalysis.SolutionCrawler
Imports Microsoft.CodeAnalysis.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
''' <summary>
''' Tests for Error List. Since it is language agnostic there are no C# or VB Specific tests
''' </summary>
<[UseExportProvider]>
Public Class DiagnosticProviderTests
Private Const s_errorElementName As String = "Error"
Private Const s_projectAttributeName As String = "Project"
Private Const s_codeAttributeName As String = "Code"
Private Const s_mappedLineAttributeName As String = "MappedLine"
Private Const s_mappedColumnAttributeName As String = "MappedColumn"
Private Const s_originalLineAttributeName As String = "OriginalLine"
Private Const s_originalColumnAttributeName As String = "OriginalColumn"
Private Const s_idAttributeName As String = "Id"
Private Const s_messageAttributeName As String = "Message"
Private Const s_originalFileAttributeName As String = "OriginalFile"
Private Const s_mappedFileAttributeName As String = "MappedFile"
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestNoErrors()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { }
</Document>
</Project>
</Workspace>
VerifyAllAvailableDiagnostics(test, Nothing)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestSingleDeclarationError()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { dontcompile }
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="64" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="64"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestLineDirective()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { dontcompile }
#line 1000
class Goo2 { dontcompile }
#line default
class Goo4 { dontcompile }
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="64" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="64"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="999" MappedColumn="65" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="65"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="5" MappedColumn="65" OriginalFile="Test.cs" OriginalLine="5" OriginalColumn="65"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestSingleBindingError()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { int a = "test"; }
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="29" Id="CS0029" MappedFile="Test.cs" MappedLine="1" MappedColumn="60" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="60"
Message=<%= String.Format(CSharpResources.ERR_NoImplicitConv, "string", "int") %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestMultipleErrorsAndWarnings()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Goo { gibberish }
class Goo2 { as; }
class Goo3 { long q = 1l; }
#pragma disable 9999999"
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="62" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="62"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="2" MappedColumn="53" OriginalFile="Test.cs" OriginalLine="2" OriginalColumn="53"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "as") %>/>
<Warning Code="78" Id="CS0078" MappedFile="Test.cs" MappedLine="3" MappedColumn="63" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="63"
Message=<%= CSharpResources.WRN_LowercaseEllSuffix %>/>
<Warning Code="1633" Id="CS1633" MappedFile="Test.cs" MappedLine="4" MappedColumn="48" OriginalFile="Test.cs" OriginalLine="4" OriginalColumn="48"
Message=<%= CSharpResources.WRN_IllegalPragma %>/>
</Diagnostics>
' Note: The below is removed because of bug # 550593.
'<Warning Code = "414" Id="CS0414" MappedFile="Test.cs" MappedLine="3" MappedColumn="58" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="58"
' Message = "The field 'Goo3.q' is assigned but its value is never used" />
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestBindingAndDeclarationErrors()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Program { void Main() { - } }
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="1525" Id="CS1525" MappedFile="Test.cs" MappedLine="1" MappedColumn="72" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="72"
Message=<%= String.Format(CSharpResources.ERR_InvalidExprTerm, "}") %>/>
<Error Code="1002" Id="CS1002" MappedFile="Test.cs" MappedLine="1" MappedColumn="72" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="72"
Message=<%= CSharpResources.ERR_SemicolonExpected %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
' Diagnostics are ordered by project-id
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestDiagnosticsFromMultipleProjects()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Program
{
-
void Test()
{
int a = 5 - "2";
}
}
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb">
Class GooClass
Sub Blah() End Sub
End Class
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics>
<Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="3" MappedColumn="44" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="44"
Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "-") %>/>
<Error Code="19" Id="CS0019" MappedFile="Test.cs" MappedLine="6" MappedColumn="56" OriginalFile="Test.cs" OriginalLine="6" OriginalColumn="56"
Message=<%= String.Format(CSharpResources.ERR_BadBinaryOps, "-", "int", "string") %>/>
<Error Code="30026" Id="BC30026" MappedFile="Test.vb" MappedLine="2" MappedColumn="44" OriginalFile="Test.vb" OriginalLine="2" OriginalColumn="44"
Message=<%= VBResources.ERR_EndSubExpected %>/>
<Error Code="30205" Id="BC30205" MappedFile="Test.vb" MappedLine="2" MappedColumn="55" OriginalFile="Test.vb" OriginalLine="2" OriginalColumn="55"
Message=<%= VBResources.ERR_ExpectedEOS %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics, ordered:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestDiagnosticsFromTurnedOff()
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Program
{
-
void Test()
{
int a = 5 - "2";
}
}
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Test.vb">
Class GooClass
Sub Blah() End Sub
End Class
</Document>
</Project>
</Workspace>
Dim diagnostics = <Diagnostics></Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics, ordered:=False, enabled:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub WarningsAsErrors()
Dim test =
<Workspace>
<Project Language="C#" CommonReferences="true">
<CompilationOptions ReportDiagnostic="Error"/>
<Document FilePath="Test.cs">
class Program
{
void Test()
{
int a = 5;
}
}
</Document>
</Project>
</Workspace>
Dim diagnostics =
<Diagnostics>
<Error Code="219" Id="CS0219"
MappedFile="Test.cs" MappedLine="5" MappedColumn="40"
OriginalFile="Test.cs" OriginalLine="5" OriginalColumn="40"
Message=<%= String.Format(CSharpResources.WRN_UnreferencedVarAssg, "a") %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub DiagnosticsInNoCompilationProjects()
Dim test =
<Workspace>
<Project Language="NoCompilation">
<Document FilePath="A.ts">
Dummy content.
</Document>
</Project>
</Workspace>
Dim diagnostics =
<Diagnostics>
<Error Id=<%= NoCompilationDocumentDiagnosticAnalyzer.Descriptor.Id %>
MappedFile="A.ts" MappedLine="0" MappedColumn="0"
OriginalFile="A.ts" OriginalLine="0" OriginalColumn="0"
Message=<%= NoCompilationDocumentDiagnosticAnalyzer.Descriptor.MessageFormat.ToString() %>/>
</Diagnostics>
VerifyAllAvailableDiagnostics(test, diagnostics)
End Sub
Private Shared Sub VerifyAllAvailableDiagnostics(test As XElement, diagnostics As XElement, Optional ordered As Boolean = True, Optional enabled As Boolean = True)
Using workspace = TestWorkspace.CreateWorkspace(test)
' turn off diagnostic
If Not enabled Then
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(ServiceComponentOnOffOptions.DiagnosticProvider, False) _
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, BackgroundAnalysisScope.Default) _
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, BackgroundAnalysisScope.Default)))
End If
Dim registrationService = workspace.Services.GetService(Of ISolutionCrawlerRegistrationService)()
registrationService.Register(workspace)
Dim diagnosticProvider = GetDiagnosticProvider(workspace)
Dim actualDiagnostics = diagnosticProvider.GetCachedDiagnosticsAsync(workspace).Result
registrationService.Unregister(workspace)
If diagnostics Is Nothing Then
Assert.Equal(0, actualDiagnostics.Length)
Else
Dim expectedDiagnostics = GetExpectedDiagnostics(workspace, diagnostics)
If ordered Then
AssertEx.Equal(expectedDiagnostics, actualDiagnostics, New Comparer())
Else
AssertEx.SetEqual(expectedDiagnostics, actualDiagnostics, New Comparer())
End If
End If
End Using
End Sub
Private Shared Function GetDiagnosticProvider(workspace As TestWorkspace) As DiagnosticAnalyzerService
Dim compilerAnalyzersMap = DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap().Add(
NoCompilationConstants.LanguageName, ImmutableArray.Create(Of DiagnosticAnalyzer)(New NoCompilationDocumentDiagnosticAnalyzer()))
Dim analyzerReference = New TestAnalyzerReferenceByLanguage(compilerAnalyzersMap)
workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences({analyzerReference}))
Dim analyzerService = New TestDiagnosticAnalyzerService()
' CollectErrors generates interleaved background and foreground tasks.
Dim service = DirectCast(workspace.Services.GetService(Of ISolutionCrawlerRegistrationService)(), SolutionCrawlerRegistrationService)
service.WaitUntilCompletion_ForTestingPurposesOnly(workspace, SpecializedCollections.SingletonEnumerable(analyzerService.CreateIncrementalAnalyzer(workspace)).WhereNotNull().ToImmutableArray())
Return analyzerService
End Function
Private Shared Function GetExpectedDiagnostics(workspace As TestWorkspace, diagnostics As XElement) As List(Of DiagnosticData)
Dim result As New List(Of DiagnosticData)
Dim mappedLine As Integer, mappedColumn As Integer, originalLine As Integer, originalColumn As Integer
Dim Id As String, message As String, originalFile As String, mappedFile As String
Dim documentId As DocumentId
For Each diagnostic As XElement In diagnostics.Elements()
mappedLine = Integer.Parse(diagnostic.Attribute(s_mappedLineAttributeName).Value)
mappedColumn = Integer.Parse(diagnostic.Attribute(s_mappedColumnAttributeName).Value)
originalLine = Integer.Parse(diagnostic.Attribute(s_originalLineAttributeName).Value)
originalColumn = Integer.Parse(diagnostic.Attribute(s_originalColumnAttributeName).Value)
Id = diagnostic.Attribute(s_idAttributeName).Value
message = diagnostic.Attribute(s_messageAttributeName).Value
originalFile = diagnostic.Attribute(s_originalFileAttributeName).Value
mappedFile = diagnostic.Attribute(s_mappedFileAttributeName).Value
documentId = GetDocumentId(workspace, originalFile)
If diagnostic.Name.LocalName.Equals(s_errorElementName) Then
result.Add(SourceError(Id, message, documentId, documentId.ProjectId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile))
Else
result.Add(SourceWarning(Id, message, documentId, documentId.ProjectId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile))
End If
Next
Return result
End Function
Private Shared Function GetProjectId(workspace As TestWorkspace, projectName As String) As ProjectId
Return (From doc In workspace.Documents
Where doc.Project.AssemblyName.Equals(projectName)
Select doc.Project.Id).Single()
End Function
Private Shared Function GetDocumentId(workspace As TestWorkspace, document As String) As DocumentId
Return (From doc In workspace.Documents
Where doc.FilePath.Equals(document)
Select doc.Id).Single()
End Function
Private Shared Function SourceError(id As String, message As String, docId As DocumentId, projId As ProjectId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer,
originalColumn As Integer, mappedFile As String, originalFile As String) As DiagnosticData
Return CreateDiagnostic(id, message, DiagnosticSeverity.Error, docId, projId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile)
End Function
Private Shared Function SourceWarning(id As String, message As String, docId As DocumentId, projId As ProjectId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer,
originalColumn As Integer, mappedFile As String, originalFile As String) As DiagnosticData
Return CreateDiagnostic(id, message, DiagnosticSeverity.Warning, docId, projId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile)
End Function
Private Shared Function CreateDiagnostic(id As String, message As String, severity As DiagnosticSeverity, docId As DocumentId, projId As ProjectId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer,
originalColumn As Integer, mappedFile As String, originalFile As String) As DiagnosticData
Return New DiagnosticData(
id:=id,
category:="test",
message:=message,
enuMessageForBingSearch:=message,
severity:=severity,
defaultSeverity:=severity,
isEnabledByDefault:=True,
warningLevel:=0,
customTags:=ImmutableArray(Of String).Empty,
properties:=ImmutableDictionary(Of String, String).Empty,
projectId:=projId,
location:=New DiagnosticDataLocation(docId, Nothing, originalFile, originalLine, originalColumn, originalLine, originalColumn, mappedFile, mappedLine, mappedColumn, mappedLine, mappedColumn),
additionalLocations:=Nothing,
language:=LanguageNames.VisualBasic,
title:=Nothing)
End Function
Private Class Comparer
Implements IEqualityComparer(Of DiagnosticData)
Public Overloads Function Equals(x As DiagnosticData, y As DiagnosticData) As Boolean Implements IEqualityComparer(Of DiagnosticData).Equals
Return x.Id = y.Id AndAlso
x.Message = y.Message AndAlso
x.Severity = y.Severity AndAlso
x.ProjectId = y.ProjectId AndAlso
x.DocumentId = y.DocumentId AndAlso
Equals(x.DataLocation?.OriginalStartLine, y.DataLocation?.OriginalStartLine) AndAlso
Equals(x.DataLocation?.OriginalStartColumn, y.DataLocation?.OriginalStartColumn)
End Function
Public Overloads Function GetHashCode(obj As DiagnosticData) As Integer Implements IEqualityComparer(Of DiagnosticData).GetHashCode
Return Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId,
Hash.Combine(obj.DocumentId,
Hash.Combine(If(obj.DataLocation?.OriginalStartLine, 0),
Hash.Combine(If(obj.DataLocation?.OriginalStartColumn, 0), obj.Severity))))))
End Function
End Class
End Class
End Namespace
|
diryboy/roslyn
|
src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb
|
Visual Basic
|
mit
| 24,309
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports Bytescout.PDF
''' <summary>
''' This example demonstrates how to create a button that launches an external resource.
''' </summary>
Class Program
Shared Sub Main()
' Create new document
Dim pdfDocument = New Document()
pdfDocument.RegistrationName = "demo"
pdfDocument.RegistrationKey = "demo"
' If you wish to load an existing document uncomment the line below And comment the Add page section instead
' pdfDocument.Load(".\existing_document.pdf")
' Add page
Dim page = New Page(PaperFormat.A4)
pdfDocument.Pages.Add(page)
' Create button
Dim button = New PushButton(20, 20, 120, 25, "button1")
button.Caption = "Launch sample.txt"
' Create action that opens an external file
Dim launchAction = New LaunchAction(IO.Path.GetFullPath("sample.txt"))
button.OnActivated = launchAction
page.Annotations.Add(button)
' Save document to file
pdfDocument.Save("result.pdf")
' Cleanup
pdfDocument.Dispose()
' Open document in default PDF viewer app
Process.Start("result.pdf")
End Sub
End Class
|
bytescout/ByteScout-SDK-SourceCode
|
PDF SDK/VB.NET/Add Launch Action in PDF/Program.vb
|
Visual Basic
|
apache-2.0
| 2,163
|
Imports Esri.ArcGIS.Mobile
Imports Esri.ArcGIS.Mobile.FeatureCaching
Imports Esri.ArcGIS.Mobile.WebServices
Imports Esri.ArcGIS.Mobile.DataProducts
Imports System.Windows.Forms
Imports System.Windows.Forms.Control
Imports System.Xml
Imports System.Diagnostics.Process
Imports System.IO
Imports System.Threading
Imports System.Resources
Imports System.Drawing
Imports Esri.ArcGISTemplates
Public Class activitySelectorMapAction
Inherits Esri.ArcGIS.Mobile.WinForms.PanMapAction
Public Event RaiseMessage(ByVal Message As String)
Public Event RaisePermMessage(ByVal Message As String, ByVal Hide As Boolean)
Private m_DownCur As System.Windows.Forms.Cursor
Private m_NormCur As System.Windows.Forms.Cursor
Private m_LastMouseLoc As Point = New Point
Private m_btn As Button
Private WithEvents m_Map As Esri.ArcGIS.Mobile.WinForms.Map
Private m_BufferDivideValue As Double
Private WithEvents m_MCActivityControl As MobileControls.AssignedWorkControl
Public Sub New()
MyBase.New()
' MyBase.
Dim s As System.IO.Stream = New System.IO.MemoryStream(My.Resources.PanCur)
m_DownCur = New System.Windows.Forms.Cursor(s)
s = New System.IO.MemoryStream(My.Resources.Finger)
m_NormCur = New System.Windows.Forms.Cursor(s)
initModule()
End Sub
#Region "Default Overrides"
Public Overrides Function ToString() As String
Return MyBase.ToString()
End Function
Protected Overrides Sub OnMapPaint(ByVal e As Esri.ArcGIS.Mobile.WinForms.MapPaintEventArgs)
MyBase.OnMapPaint(e)
End Sub
Protected Overrides Sub OnMapMouseWheel(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs)
MyBase.OnMapMouseWheel(e)
End Sub
Protected Overrides Sub OnMapMouseMove(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs)
MyBase.OnMapMouseMove(e)
End Sub
Protected Overrides Sub OnMapKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
MyBase.OnMapKeyUp(e)
End Sub
Protected Overrides Sub OnMapKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
MyBase.OnMapKeyPress(e)
End Sub
Protected Overrides Sub OnMapKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
MyBase.OnMapKeyDown(e)
End Sub
Protected Overrides Sub OnActiveChanging(ByVal active As Boolean)
Try
'Me.Activating
MyBase.OnActiveChanging(active)
Catch ex As Exception
End Try
End Sub
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()
End Function
Protected Overrides Sub Finalize()
MyBase.Finalize()
If m_btn IsNot Nothing Then
If m_btn.Parent IsNot Nothing Then
m_btn.Parent.Controls.Remove(m_btn)
End If
m_btn.Dispose()
End If
m_btn = Nothing
If m_Map IsNot Nothing Then
m_Map.Dispose()
End If
m_Map = Nothing
End Sub
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Return MyBase.Equals(obj)
End Function
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
MyBase.Dispose(disposing)
End Sub
Public Overrides Sub Cancel()
MyBase.Cancel()
End Sub
Protected Overrides Sub OnActiveChanged(ByVal active As Boolean)
MyBase.OnActiveChanged(active)
End Sub
#End Region
Private Sub FixZoom(ByVal bOut As Boolean, ByVal xCent As Double, ByVal yCent As Double)
'Make sure the map is valid
If m_Map Is Nothing Then Return
If m_Map.IsValid = False Then Return
'Determine which direction to zoom
If (bOut) Then
Dim pExt As Esri.ArcGIS.Mobile.Geometries.Envelope
'Get the map extent
pExt = m_Map.Extent()
'Resize it
pExt.Resize(1.5)
'Center it
pExt.CenterAt(xCent, yCent)
'Set the map extent
m_Map.Extent = pExt
'cleanup
pExt = Nothing
Else
Dim pExt As Esri.ArcGIS.Mobile.Geometries.Envelope
'Get the map extent
pExt = m_Map.Extent()
'Resize it
pExt.Resize(0.5)
'Center it
pExt.CenterAt(xCent, yCent)
'Set the map extent
m_Map.Extent = pExt
'cleanup
pExt = Nothing
End If
End Sub
#Region "Public Functions"
Public Function getCrew() As String
Return m_MCActivityControl.getCrew()
End Function
Public Function getWO() As String
Return m_MCActivityControl.getWO()
End Function
Public Function getText() As String
Return m_MCActivityControl.getText()
End Function
Public Function addActivityButton(Optional ByVal TopX As Integer = -1, Optional ByVal TopY As Integer = -1) As Boolean
Try
'Adds the ID button to the map display
If m_btn Is Nothing Then
'Create a new button
m_btn = New Button
With m_btn
'Set the button defaults
.BackColor = System.Drawing.SystemColors.Info
.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch
.FlatAppearance.BorderSize = 0
.FlatStyle = System.Windows.Forms.FlatStyle.Flat
.BackgroundImage = Global.MobileControls.My.Resources.Resources.ActivitySelector
.Name = "btnID"
.Size = New System.Drawing.Size(50, 50)
.UseVisualStyleBackColor = False
'Add a handler for the click event
AddHandler .MouseClick, AddressOf ActivityBtnClick
'Set the id button on the top right
TopX = m_Map.Width - 25
TopY = 145
.Location = New System.Drawing.Point(TopX, TopY)
'Add a handler to relocate the button a map resize
AddHandler m_Map.Resize, AddressOf resize
End With
'Add the button to the map
m_Map.Controls.Add(m_btn)
End If
'Create the layer combo
Catch ex As Exception
Return False
End Try
Return True
End Function
Public Property ManualSetMap As Esri.ArcGIS.Mobile.WinForms.Map
Get
Return Map
End Get
Set(value As Esri.ArcGIS.Mobile.WinForms.Map)
m_Map = value
End Set
End Property
Public Sub InitActivityForm(panel As Control)
'Create the new activity control
m_MCActivityControl = New AssignedWorkControl(m_Map)
'Set to dock it full
m_MCActivityControl.Dock = DockStyle.Fill
'Add the control to the panel to house it
panel.Controls.Add(m_MCActivityControl)
End Sub
Protected Overrides Sub OnSetMap(ByVal map As Esri.ArcGIS.Mobile.WinForms.Map)
MyBase.OnSetMap(map)
'm_Map = map
End Sub
#End Region
#Region "Events"
Private Sub ActivityBtnClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Activates/Deactivate the mapaction and changes the button
Dim pBtn As Button = CType(sender, Button)
If m_Map.MapAction Is Me Then
m_Map.MapAction = Nothing
pBtn.BackgroundImage = Global.MobileControls.My.Resources.Resources.ActivitySelector
Else
m_Map.MapAction = Me
pBtn.BackgroundImage = Global.MobileControls.My.Resources.Resources.ActivitySelectorDown
End If
End Sub
Private Sub resize()
'For Each item As String In m_layCBO.Items
'Next
'relocates the button and combo on a map resize
If m_btn IsNot Nothing And m_Map IsNot Nothing Then
m_btn.Location = New System.Drawing.Point(m_Map.Width - 80, 145)
End If
End Sub
#End Region
#Region "PrivateFunctions"
Private Sub initModule()
Try
Dim strVal As String = GlobalsFunctions.appConfig.IDPanel.SearchTolerence
If Not IsNumeric(strVal) Then
m_BufferDivideValue = 15
Else
m_BufferDivideValue = CDbl(strVal)
End If
strVal = GlobalsFunctions.appConfig.ApplicationSettings.FontSize
Catch ex As Exception
Dim st As New StackTrace
MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message)
st = Nothing
Finally
''myutils = Nothing
End Try
End Sub
#End Region
#Region "Properties"
#End Region
#Region "Overrides"
Protected Overrides Sub OnMapMouseDown(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs)
m_LastMouseLoc = e.Location
'm_map.SuspendLayout()
'm_map.SuspendOnPaint = True
'MyBase.OnMapMouseDown(e)
m_Map.Cursor = m_DownCur
MyBase.OnMapMouseDown(e)
End Sub
Protected Overrides Sub OnMapMouseUp(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs)
If Me.Active = False Then Return
If e.Clicks > 1 Then Return
Try
'If m_EditFrm.Visible = True And m_SetGeoOnly = False Then Return
If m_LastMouseLoc.Equals(e.Location) Then
CheckForActivityAtLocation(e.MapCoordinate)
End If
Catch ex As Exception
Finally
MyBase.OnMapMouseUp(e)
m_Map.Cursor = m_NormCur
End Try
End Sub
Public Sub CheckForActivityAtLocation(ByVal coord As Esri.ArcGIS.Mobile.Geometries.Coordinate, Optional ByVal LayerName As String = "")
' If e.Clicks > 1 Then Return
If m_Map.IsValid = False Then Return
m_MCActivityControl.selectWOatLocation(coord)
End Sub
#End Region
Private Sub m_MCActivityControl_RaiseMessage(Message As String) Handles m_MCActivityControl.RaiseMessage
RaiseEvent RaiseMessage(Message)
End Sub
Private Sub m_MCActivityControl_RaisePermMessage(Message As String, Hide As Boolean) Handles m_MCActivityControl.RaisePermMessage
RaiseEvent RaisePermMessage(Message, Hide)
End Sub
Private Sub activitySelectorMapAction_StatusChanged(sender As Object, e As WinForms.MapActionStatusChangedEventArgs) Handles Me.StatusChanged
Try
'Check the map actions status
If e.StatusId = Esri.ArcGIS.Mobile.WinForms.MapAction.Activated Then
'If the button has been created, update the buttons image
If m_btn IsNot Nothing Then
m_btn.BackgroundImage = My.Resources.ActivitySelectorDown
End If
ElseIf e.StatusId = Esri.ArcGIS.Mobile.WinForms.MapAction.Deactivated Then
'If the button has been created, update the buttons image
If m_btn IsNot Nothing Then
m_btn.BackgroundImage = My.Resources.ActivitySelector
End If
End If
Catch ex As Exception
Dim st As New StackTrace
MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message)
st = Nothing
Return
End Try
End Sub
Public Event WOChanged(WOOID As String, WOCrew As String, WODisplayText As String)
Private Sub m_MCActivityControl_WOChanged(WOOID As String, WOCrew As String, WODisplayText As String) Handles m_MCActivityControl.WOChanged
RaiseEvent WOChanged(WOOID, WOCrew, WODisplayText)
End Sub
End Class
|
Esri/water-utility-mobile-map
|
Activity_Control/activitySelectorMapAction.vb
|
Visual Basic
|
apache-2.0
| 11,868
|
Public Class DisplayOptions
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
Friend WithEvents lblItem As System.Windows.Forms.Label
Friend WithEvents lblColor As System.Windows.Forms.Label
Friend WithEvents lblFont As System.Windows.Forms.Label
Friend WithEvents lblLine As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents Button3 As System.Windows.Forms.Button
Friend WithEvents cmbColor As System.Windows.Forms.ComboBox
Friend WithEvents cmbFont As System.Windows.Forms.ComboBox
Friend WithEvents ComboBox3 As System.Windows.Forms.ComboBox
Friend WithEvents Button4 As System.Windows.Forms.Button
Friend WithEvents NumericUpDown1 As System.Windows.Forms.NumericUpDown
Friend WithEvents Label1 As System.Windows.Forms.Label
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.ListBox1 = New System.Windows.Forms.ListBox()
Me.lblItem = New System.Windows.Forms.Label()
Me.lblColor = New System.Windows.Forms.Label()
Me.lblFont = New System.Windows.Forms.Label()
Me.lblLine = New System.Windows.Forms.Label()
Me.Button1 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
Me.cmbColor = New System.Windows.Forms.ComboBox()
Me.cmbFont = New System.Windows.Forms.ComboBox()
Me.ComboBox3 = New System.Windows.Forms.ComboBox()
Me.Button4 = New System.Windows.Forms.Button()
Me.NumericUpDown1 = New System.Windows.Forms.NumericUpDown()
Me.Label1 = New System.Windows.Forms.Label()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'ListBox1
'
Me.ListBox1.Items.AddRange(New Object() {"Backgorund", "Axes", "Labels", "Numbers", "Lines (unchanged)", "Lines (changed)", "Lines (disabled)", "Grid", "Difference"})
Me.ListBox1.Location = New System.Drawing.Point(8, 24)
Me.ListBox1.Name = "ListBox1"
Me.ListBox1.Size = New System.Drawing.Size(224, 121)
Me.ListBox1.TabIndex = 0
'
'lblItem
'
Me.lblItem.Location = New System.Drawing.Point(8, 8)
Me.lblItem.Name = "lblItem"
Me.lblItem.Size = New System.Drawing.Size(100, 20)
Me.lblItem.TabIndex = 1
Me.lblItem.Text = "Display Items:"
'
'lblColor
'
Me.lblColor.Location = New System.Drawing.Point(248, 24)
Me.lblColor.Name = "lblColor"
Me.lblColor.Size = New System.Drawing.Size(40, 24)
Me.lblColor.TabIndex = 2
Me.lblColor.Text = "Color"
'
'lblFont
'
Me.lblFont.Location = New System.Drawing.Point(248, 56)
Me.lblFont.Name = "lblFont"
Me.lblFont.Size = New System.Drawing.Size(40, 20)
Me.lblFont.TabIndex = 3
Me.lblFont.Text = "Font"
'
'lblLine
'
Me.lblLine.Location = New System.Drawing.Point(248, 88)
Me.lblLine.Name = "lblLine"
Me.lblLine.Size = New System.Drawing.Size(40, 20)
Me.lblLine.TabIndex = 4
Me.lblLine.Text = "Line"
'
'Button1
'
Me.Button1.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Button1.Location = New System.Drawing.Point(248, 120)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(80, 24)
Me.Button1.TabIndex = 6
Me.Button1.Text = "&OK"
'
'Button2
'
Me.Button2.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Button2.Location = New System.Drawing.Point(344, 120)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(72, 24)
Me.Button2.TabIndex = 7
Me.Button2.Text = "&Cancel"
'
'Button3
'
Me.Button3.Location = New System.Drawing.Point(432, 120)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(75, 24)
Me.Button3.TabIndex = 8
Me.Button3.Text = "&Help"
'
'cmbColor
'
Me.cmbColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed
Me.cmbColor.Location = New System.Drawing.Point(288, 24)
Me.cmbColor.Name = "cmbColor"
Me.cmbColor.Size = New System.Drawing.Size(128, 21)
Me.cmbColor.TabIndex = 9
'
'cmbFont
'
Me.cmbFont.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmbFont.Location = New System.Drawing.Point(288, 56)
Me.cmbFont.Name = "cmbFont"
Me.cmbFont.Size = New System.Drawing.Size(128, 22)
Me.cmbFont.TabIndex = 10
Me.cmbFont.Text = "Arial"
'
'ComboBox3
'
Me.ComboBox3.Location = New System.Drawing.Point(288, 88)
Me.ComboBox3.Name = "ComboBox3"
Me.ComboBox3.Size = New System.Drawing.Size(128, 21)
Me.ComboBox3.TabIndex = 11
'
'Button4
'
Me.Button4.Location = New System.Drawing.Point(424, 24)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(80, 24)
Me.Button4.TabIndex = 12
Me.Button4.Text = "Custom..."
'
'NumericUpDown1
'
Me.NumericUpDown1.Location = New System.Drawing.Point(456, 56)
Me.NumericUpDown1.Name = "NumericUpDown1"
Me.NumericUpDown1.Size = New System.Drawing.Size(48, 20)
Me.NumericUpDown1.TabIndex = 13
'
'Label1
'
Me.Label1.Location = New System.Drawing.Point(424, 56)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(32, 16)
Me.Label1.TabIndex = 14
Me.Label1.Text = "Size"
'
'DisplayOptions
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(514, 152)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label1, Me.NumericUpDown1, Me.Button4, Me.ComboBox3, Me.cmbFont, Me.cmbColor, Me.Button3, Me.Button2, Me.Button1, Me.lblLine, Me.lblFont, Me.lblColor, Me.ListBox1, Me.lblItem})
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.Name = "DisplayOptions"
Me.ShowInTaskbar = False
Me.Text = "Display Options"
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
#End Region
Private Colors As Color() = {Color.AliceBlue, Color.AntiqueWhite, Color.Aqua, Color.Aquamarine, Color.Azure, Color.Beige, Color.Black, Color.Bisque, Color.BlanchedAlmond, Color.Blue, Color.BlueViolet, Color.Brown, Color.BurlyWood, Color.CadetBlue, Color.Chartreuse, Color.Chocolate, Color.Coral, Color.CornflowerBlue, Color.Cornsilk, Color.Crimson, Color.Cyan, Color.DarkBlue}
Private Sub DisplayOptions_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
For i = 0 To Colors.GetUpperBound(0)
cmbColor.Items.Add(vbTab & Colors(i).ToString)
Next
End Sub
Private Sub cmbColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles cmbColor.DrawItem
Dim G As Graphics = e.Graphics
G.FillRectangle(New SolidBrush(Colors(e.Index)), 2, 2, 15, 10)
G.DrawRectangle(New Pen(Color.Black), 2, 2, 15, 10)
G.DrawString(Colors(e.Index).ToString, New Font("Arial", 8), New SolidBrush(Color.Black), 16, 5)
Me.Text = e.Index.ToString
End Sub
End Class
|
oliveralatkovic/isaac
|
isaac/DisplayOptions.vb
|
Visual Basic
|
bsd-3-clause
| 8,839
|
' SearchResult.aspx.vb
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Public Class SearchPage Inherits System.Web.UI.Page
Protected txtInput As TextBox
Protected cmdSearch As Button
Protected lblResult As Label Protected
Sub cmdSearch _Click(Source As Object, _ e As EventArgs)
// Do Search…..
// …………
lblResult.Text="You Searched for: " & txtInput.Text
// Display Search Results…..
// …………
End Sub
End Class
|
frizb/SourceCodeSniffer
|
samples/VisualBasic XSS 1.vb
|
Visual Basic
|
bsd-3-clause
| 515
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ProntoCmsWebApplication.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
|
xingh/prontocms
|
Project Templates/VB/ProntoCmsWebApplication/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,788
|
Public Class MeetingNotifier
Private peopleFinder As IPeopleFinder
Private smsSender As ISmsSender
Private groupName As String
Public Sub New(ByVal groupName As String, ByVal peopleFinder As IPeopleFinder, ByVal smsSender As ISmsSender)
Me.peopleFinder = peopleFinder
Me.smsSender = smsSender
Me.groupName = groupName
End Sub
Public Sub NotifyMeetingTime(ByVal newMeeetingTime As System.DateTime, ByVal location As String)
For Each name As String In peopleFinder.GetPeopleInGroup(groupName)
Dim msgToSend As String = "new meeting in " & location & " at " & newMeeetingTime
smsSender.SendSMS(name, msgToSend)
Next
End Sub
End Class
|
codechip/rhino-tools
|
SampleApplications/InteractionBasedTesting/Rhino.Mocks.Demo.VB/MeetingNotifier.vb
|
Visual Basic
|
bsd-3-clause
| 680
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Collections
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a .NET assembly. An assembly consists of one or more modules.
''' </summary>
Friend MustInherit Class AssemblySymbol
Inherits Symbol
Implements IAssemblySymbol
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version of Symbol.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll.
''' The value is provided by ReferenceManager and must not be modified. For SourceAssemblySymbol, non-missing
''' coreLibrary must match one of the referenced assemblies returned by GetReferencedAssemblySymbols() method of
''' the main module. If there is no existing assembly that can be used as a source for the primitive types,
''' the value is a Compilation.MissingCorLibrary.
''' </summary>
Private _corLibrary As AssemblySymbol
''' <summary>
''' The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll.
''' The value is a MissingAssemblySymbol if none of the referenced assemblies can be used as a source for the
''' primitive types and the owning assembly cannot be used as the source too. Otherwise, it is one of
''' the referenced assemblies returned by GetReferencedAssemblySymbols() method or the owning assembly.
''' </summary>
Friend ReadOnly Property CorLibrary As AssemblySymbol
Get
Return _corLibrary
End Get
End Property
''' <summary>
''' A helper method for ReferenceManager to set the system assembly, which provides primitive
''' types like Object, String, etc., e.g. mscorlib.dll.
''' </summary>
''' <param name="corLibrary"></param>
Friend Sub SetCorLibrary(corLibrary As AssemblySymbol)
Debug.Assert(_corLibrary Is Nothing)
_corLibrary = corLibrary
End Sub
''' <summary>
''' Simple name of the assembly.
''' </summary>
''' <remarks>
''' This is equivalent to <see cref="Identity"/>.<see cref="AssemblyIdentity.Name"/>, but may be
''' much faster to retrieve for source code assemblies, since it does not require binding the assembly-level
''' attributes that contain the version number and other assembly information.
''' </remarks>
Public Overrides ReadOnly Property Name As String
Get
Return Identity.Name
End Get
End Property
''' <summary>
''' True if the assembly contains interactive code.
''' </summary>
Public Overridable ReadOnly Property IsInteractive As Boolean Implements IAssemblySymbol.IsInteractive
Get
Return False
End Get
End Property
''' <summary>
''' Get the name of this assembly.
''' </summary>
Public MustOverride ReadOnly Property Identity As AssemblyIdentity Implements IAssemblySymbol.Identity
''' <summary>
''' Target architecture of the machine.
''' </summary>
Friend ReadOnly Property Machine As System.Reflection.PortableExecutable.Machine
Get
Return Modules(0).Machine
End Get
End Property
''' <summary>
''' Indicates that this PE file makes Win32 calls. See CorPEKind.pe32BitRequired for more information (http://msdn.microsoft.com/en-us/library/ms230275.aspx).
''' </summary>
Friend ReadOnly Property Bit32Required As Boolean
Get
Return Modules(0).Bit32Required
End Get
End Property
''' <summary>
''' Gets a read-only list of all the modules in this assembly. (There must be at least one.) The first one is the main module
''' that holds the assembly manifest.
''' </summary>
Public MustOverride ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
''' <summary>
''' Gets the merged root namespace that contains all namespaces and types defined in the modules
''' of this assembly. If there is just one module in this assembly, this property just returns the
''' GlobalNamespace of that module.
''' </summary>
Public MustOverride ReadOnly Property GlobalNamespace As NamespaceSymbol
''' <summary>
''' Given a namespace symbol, returns the corresponding assembly specific namespace symbol
''' </summary>
Friend Function GetAssemblyNamespace(namespaceSymbol As NamespaceSymbol) As NamespaceSymbol
If namespaceSymbol.IsGlobalNamespace Then
Return Me.GlobalNamespace
End If
Dim container As NamespaceSymbol = namespaceSymbol.ContainingNamespace
If container Is Nothing Then
Return Me.GlobalNamespace
End If
If namespaceSymbol.Extent.Kind = NamespaceKind.Assembly AndAlso namespaceSymbol.ContainingAssembly = Me Then
Return namespaceSymbol
End If
Dim assemblyContainer As NamespaceSymbol = GetAssemblyNamespace(container)
If assemblyContainer Is container Then
' Trivial case, container isn't merged.
Return namespaceSymbol
End If
If assemblyContainer Is Nothing Then
Return Nothing
End If
Return assemblyContainer.GetNestedNamespace(namespaceSymbol.Name)
End Function
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Assembly
End Get
End Property
Public NotOverridable Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitAssembly(Me, arg)
End Function
Friend Sub New()
' Only the compiler can create AssemblySymbols.
End Sub
''' <summary>
''' Does this symbol represent a missing assembly.
''' </summary>
Friend MustOverride ReadOnly Property IsMissing As Boolean
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
''' This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' Lookup a top level type referenced from metadata, names should be
''' compared case-sensitively.
''' </summary>
''' <param name="emittedName">
''' Full type name with generic name mangling.
''' </param>
''' <param name="digThroughForwardedTypes">
''' Take forwarded types into account.
''' </param>
''' <remarks></remarks>
Friend Function LookupTopLevelMetadataType(ByRef emittedName As MetadataTypeName, digThroughForwardedTypes As Boolean) As NamedTypeSymbol
Return LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies:=Nothing, digThroughForwardedTypes:=digThroughForwardedTypes)
End Function
''' <summary>
''' Lookup a top level type referenced from metadata, names should be
''' compared case-sensitively. Detect cycles during lookup.
''' </summary>
''' <param name="emittedName">
''' Full type name, possibly with generic name mangling.
''' </param>
''' <param name="visitedAssemblies">
''' List of assemblies lookup has already visited (since type forwarding can introduce cycles).
''' </param>
''' <param name="digThroughForwardedTypes">
''' Take forwarded types into account.
''' </param>
Friend MustOverride Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol
''' <summary>
''' Returns the type symbol for a forwarded type based its canonical CLR metadata name.
''' The name should refer to a non-nested type. If type with this name Is Not forwarded,
''' null Is returned.
''' </summary>
Public Function ResolveForwardedType(fullyQualifiedMetadataName As String) As NamedTypeSymbol
If fullyQualifiedMetadataName Is Nothing Then
Throw New ArgumentNullException(NameOf(fullyQualifiedMetadataName))
End If
Dim emittedName = MetadataTypeName.FromFullName(fullyQualifiedMetadataName)
Return TryLookupForwardedMetadataType(emittedName, ignoreCase:=False)
End Function
''' <summary>
''' Look up the given metadata type, if it Is forwarded.
''' </summary>
Friend Function TryLookupForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean) As NamedTypeSymbol
Return TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies:=Nothing, ignoreCase:=ignoreCase)
End Function
''' <summary>
''' Look up the given metadata type, if it is forwarded.
''' </summary>
Friend Overridable Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
Return Nothing
End Function
Friend Function CreateCycleInTypeForwarderErrorTypeSymbol(ByRef emittedName As MetadataTypeName) As ErrorTypeSymbol
Dim diagInfo As DiagnosticInfo = New DiagnosticInfo(MessageProvider.Instance, ERRID.ERR_TypeFwdCycle2, emittedName.FullName, Me)
Return New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Me.Modules(0), emittedName, diagInfo)
End Function
''' <summary>
''' Lookup declaration for predefined CorLib type in this Assembly. Only valid if this
''' assembly is the Cor Library
''' </summary>
''' <param name="type"></param>
''' <returns></returns>
''' <remarks></remarks>
Friend MustOverride Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol
''' <summary>
''' Register declaration of predefined CorLib type in this Assembly.
''' </summary>
''' <param name="corType"></param>
Friend Overridable Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol)
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Continue looking for declaration of predefined CorLib type in this Assembly
''' while symbols for new type declarations are constructed.
''' </summary>
Friend Overridable ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
''' <summary>
''' Return an array of assemblies involved in canonical type resolution of
''' NoPia local types defined within this assembly. In other words, all
''' references used by previous compilation referencing this assembly.
''' </summary>
''' <returns></returns>
Friend MustOverride Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Friend MustOverride Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
''' <summary>
''' Return an array of assemblies referenced by this assembly, which are linked (/l-ed) by
''' each compilation that is using this AssemblySymbol as a reference.
''' If this AssemblySymbol is linked too, it will be in this array too.
''' </summary>
Friend MustOverride Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
Friend MustOverride Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
''' <summary>
''' Assembly is /l-ed by compilation that is using it as a reference.
''' </summary>
Friend MustOverride ReadOnly Property IsLinked As Boolean
''' <summary>
''' Returns true and a string from the first GuidAttribute on the assembly,
''' the string might be null or an invalid guid representation. False,
''' if there is no GuidAttribute with string argument.
''' </summary>
Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean
Return GetGuidStringDefaultImplementation(guidString)
End Function
Public MustOverride ReadOnly Property TypeNames As ICollection(Of String) Implements IAssemblySymbol.TypeNames
Public MustOverride ReadOnly Property NamespaceNames As ICollection(Of String) Implements IAssemblySymbol.NamespaceNames
''' <summary>
''' An empty list means there was no IVT attribute with matching <paramref name="simpleName"/>.
''' An IVT attribute without a public key setting is represented by an entry that is empty in the returned list
''' </summary>
''' <param name="simpleName"></param>
''' <returns></returns>
''' <remarks></remarks>
Friend MustOverride Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
Friend MustOverride Function AreInternalsVisibleToThisAssembly(other As AssemblySymbol) As Boolean
''' <summary>
''' Get symbol for predefined type from Cor Library used by this assembly.
''' </summary>
''' <param name="type"></param>
''' <returns>The symbol for the pre-defined type or Nothing if the type is not defined in the core library</returns>
''' <remarks></remarks>
Friend Function GetSpecialType(type As SpecialType) As NamedTypeSymbol
If type <= SpecialType.None OrElse type > SpecialType.Count Then
Throw New ArgumentOutOfRangeException()
End If
Return CorLibrary.GetDeclaredSpecialType(type)
End Function
''' <summary>
''' The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
''' Error if there was no COR Library in a compilation using the assembly.
'''</summary>
Friend ReadOnly Property ObjectType As NamedTypeSymbol
Get
Return GetSpecialType(SpecialType.System_Object)
End Get
End Property
''' <summary>
''' Get symbol for predefined type from Cor Library used by this assembly.
''' </summary>
''' <param name="type"></param>
''' <returns></returns>
''' <remarks></remarks>
Friend Function GetPrimitiveType(type As Microsoft.Cci.PrimitiveTypeCode) As NamedTypeSymbol
Return GetSpecialType(SpecialTypes.GetTypeFromMetadataName(type))
End Function
''' <summary>
''' Lookup a type within the assembly using its canonical CLR metadata name (names are compared case-sensitively).
''' </summary>
''' <param name="fullyQualifiedMetadataName">
''' </param>
''' <returns>
''' Symbol for the type or null if type cannot be found or is ambiguous.
''' </returns>
Public Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol
Return GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=False, isWellKnownType:=False)
End Function
Private Shared ReadOnly s_nestedTypeNameSeparators As Char() = {"+"c}
''' <summary>
''' Lookup a type within the assembly using its canonical CLR metadata name (names are compared case-sensitively).
''' </summary>
''' <param name="metadataName"></param>
''' <param name="includeReferences">
''' If search within assembly fails, lookup in assemblies referenced by the primary module.
''' For source assembly, this is equivalent to all assembly references given to compilation.
''' </param>
''' <param name="isWellKnownType">
''' Extra restrictions apply when searching for a well-known type. In particular, the type must be public.
''' </param>
''' <param name="useCLSCompliantNameArityEncoding">
''' While resolving the name, consider only types following CLS-compliant generic type names and arity encoding (ECMA-335, section 10.7.2).
''' I.e. arity is inferred from the name and matching type must have the same emitted name and arity.
''' </param>
''' <returns></returns>
Friend Function GetTypeByMetadataName(metadataName As String, includeReferences As Boolean, isWellKnownType As Boolean, Optional useCLSCompliantNameArityEncoding As Boolean = False) As NamedTypeSymbol
If metadataName Is Nothing Then
Throw New ArgumentNullException(NameOf(metadataName))
End If
Dim type As NamedTypeSymbol = Nothing
Dim mdName As MetadataTypeName
If metadataName.Contains("+"c) Then
Dim parts() As String = metadataName.Split(s_nestedTypeNameSeparators)
If parts.Length > 0 Then
mdName = MetadataTypeName.FromFullName(parts(0), useCLSCompliantNameArityEncoding)
type = GetTopLevelTypeByMetadataName(mdName, includeReferences, isWellKnownType)
Dim i As Integer = 1
While type IsNot Nothing AndAlso Not type.IsErrorType() AndAlso i < parts.Length
mdName = MetadataTypeName.FromTypeName(parts(i))
Dim temp = type.LookupMetadataType(mdName)
type = If(Not isWellKnownType OrElse IsValidWellKnownType(temp), temp, Nothing)
i += 1
End While
End If
Else
mdName = MetadataTypeName.FromFullName(metadataName, useCLSCompliantNameArityEncoding)
type = GetTopLevelTypeByMetadataName(mdName, includeReferences, isWellKnownType)
End If
Return If(type Is Nothing OrElse type.IsErrorType(), Nothing, type)
End Function
''' <summary>
''' Lookup a top level type within the assembly or one of the assemblies reeferenced by the primary module,
''' names are compared case-sensitively. In case of ambiguity, type from this assembly wins,
''' otherwise Nothing is returned.
''' </summary>
''' <returns>
''' Symbol for the type or Nothing if type cannot be found or ambiguous.
''' </returns>
Friend Function GetTopLevelTypeByMetadataName(ByRef metadataName As MetadataTypeName, includeReferences As Boolean, isWellKnownType As Boolean) As NamedTypeSymbol
Dim result As NamedTypeSymbol
' First try this assembly
result = Me.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False)
If isWellKnownType AndAlso Not IsValidWellKnownType(result) Then
result = Nothing
End If
If (IsAcceptableMatchForGetTypeByNameAndArity(result)) Then
Return result
End If
result = Nothing
If includeReferences Then
' Lookup in references
Dim references As ImmutableArray(Of AssemblySymbol) = Me.Modules(0).GetReferencedAssemblySymbols()
For i As Integer = 0 To references.Length - 1 Step 1
Debug.Assert(Not (TypeOf Me Is SourceAssemblySymbol AndAlso references(i).IsMissing)) ' Non-source assemblies can have missing references
Dim candidate As NamedTypeSymbol = references(i).LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False)
If isWellKnownType AndAlso Not IsValidWellKnownType(candidate) Then
candidate = Nothing
End If
If IsAcceptableMatchForGetTypeByNameAndArity(candidate) AndAlso Not candidate.IsHiddenByEmbeddedAttribute() AndAlso candidate <> result Then
If (result IsNot Nothing) Then
' Ambiguity
Return Nothing
End If
result = candidate
End If
Next
End If
Return result
End Function
Friend Shared Function IsAcceptableMatchForGetTypeByNameAndArity(candidate As NamedTypeSymbol) As Boolean
Return candidate IsNot Nothing AndAlso (candidate.Kind <> SymbolKind.ErrorType OrElse Not (TypeOf candidate Is MissingMetadataTypeSymbol))
End Function
''' <summary>
''' If this property returns false, it is certain that there are no extension
''' methods (from language perspective) inside this assembly. If this property returns true,
''' it is highly likely (but not certain) that this type contains extension methods.
''' This property allows the search for extension methods to be narrowed much more quickly.
'''
''' !!! Note that this property can mutate during lifetime of the symbol !!!
''' !!! from True to False, as we learn more about the assembly. !!!
''' </summary>
Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements IAssemblySymbol.MightContainExtensionMethods
Friend MustOverride ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Protected Enum IVTConclusion
Match
OneSignedOneNot
PublicKeyDoesntMatch
NoRelationshipClaimed
End Enum
Protected Function PerformIVTCheck(key As ImmutableArray(Of Byte), otherIdentity As AssemblyIdentity) As IVTConclusion
' Implementation of this function in C# compiler is somewhat different, but we believe
' that the difference doesn't affect any real world scenarios that we know/care about.
' At the moment we don't feel it is worth porting the logic, but we might reconsider in the future.
' We also have an easy out here. Suppose Smith names Jones as a friend, And Jones Is
' being compiled as a module, Not as an assembly. You can only strong-name an assembly. So if this module
' Is named Jones, And Smith Is extending friend access to Jones, then we are going to optimistically
' assume that Jones Is going to be compiled into an assembly with a matching strong name, if necessary.
Dim compilation As Compilation = Me.DeclaringCompilation
If compilation IsNot Nothing AndAlso compilation.Options.OutputKind.IsNetModule() Then
Return IVTConclusion.Match
End If
Dim result As IVTConclusion
If Me.PublicKey.IsDefaultOrEmpty OrElse key.IsDefaultOrEmpty Then
If Me.PublicKey.IsDefaultOrEmpty AndAlso key.IsDefaultOrEmpty Then
'we are not signed, therefore the other assembly shouldn't be signed
result = If(otherIdentity.IsStrongName, IVTConclusion.OneSignedOneNot, IVTConclusion.Match)
ElseIf Me.PublicKey.IsDefaultOrEmpty Then
result = IVTConclusion.PublicKeyDoesntMatch
Else
' key is NullOrEmpty, Me.PublicKey is not.
result = IVTConclusion.NoRelationshipClaimed
End If
ElseIf ByteSequenceComparer.Equals(key, Me.PublicKey) Then
result = If(otherIdentity.IsStrongName, IVTConclusion.Match, IVTConclusion.OneSignedOneNot)
Else
result = IVTConclusion.PublicKeyDoesntMatch
End If
Return result
End Function
Friend Function IsValidWellKnownType(result As NamedTypeSymbol) As Boolean
If result Is Nothing OrElse result.TypeKind = TypeKind.Error Then
Return False
End If
Debug.Assert(result.ContainingType Is Nothing OrElse IsValidWellKnownType(result.ContainingType),
"Checking the containing type is the caller's responsibility.")
Return result.DeclaredAccessibility = Accessibility.Public OrElse IsSymbolAccessible(result, Me)
End Function
#Region "IAssemblySymbol"
Private ReadOnly Property IAssemblySymbol_GlobalNamespace As INamespaceSymbol Implements IAssemblySymbol.GlobalNamespace
Get
Return Me.GlobalNamespace
End Get
End Property
Private Function IAssemblySymbol_GivesAccessTo(toAssembly As IAssemblySymbol) As Boolean Implements IAssemblySymbol.GivesAccessTo
If Equals(Me, toAssembly) Then
Return True
End If
Dim assembly = TryCast(toAssembly, AssemblySymbol)
If assembly Is Nothing Then
Return False
End If
Dim myKeys = Me.GetInternalsVisibleToPublicKeys(assembly.Identity.Name)
For Each key In myKeys
If assembly.PerformIVTCheck(key, Me.Identity) = IVTConclusion.Match Then
Return True
End If
Next
Return False
End Function
Private ReadOnly Property IAssemblySymbol_Modules As IEnumerable(Of IModuleSymbol) Implements IAssemblySymbol.Modules
Get
Return Me.Modules
End Get
End Property
Private Function IAssemblySymbol_ResolveForwardedType(metadataName As String) As INamedTypeSymbol Implements IAssemblySymbol.ResolveForwardedType
Return Me.ResolveForwardedType(metadataName)
End Function
Private Function IAssemblySymbol_GetTypeByMetadataName(metadataName As String) As INamedTypeSymbol Implements IAssemblySymbol.GetTypeByMetadataName
Return Me.GetTypeByMetadataName(metadataName)
End Function
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitAssembly(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAssembly(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitAssembly(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAssembly(Me)
End Function
#End Region
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/AssemblySymbol.vb
|
Visual Basic
|
apache-2.0
| 29,765
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.Peek
Imports Microsoft.CodeAnalysis.Editor.Peek
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.Imaging.Interop
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.Text
Imports Moq
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Peek
Public Class PeekTests
<WpfFact, WorkItem(820706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820706"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestInvokeInEmptyFile()
Dim result = GetPeekResultCollection(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$}</Document>
</Project>
</Workspace>)
Assert.Null(result)
End Sub
<WpfFact, WorkItem(827025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827025"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestWorksAcrossLanguages()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="C#" AssemblyName="Reference" CommonReferences="true">
<Document>public class {|Identifier:TestClass|} { }</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>Reference</ProjectReference>
<Document>
Public Class Blah : Inherits $$TestClass : End Class
</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(index:=0, name:="Identifier")
End Using
End Sub
<WpfFact, WorkItem(824336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824336"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestPeekDefinitionWhenInvokedOnLiteral()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class C { string s = $$"Goo"; }</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"String [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"String [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("String", StringComparison.Ordinal))
End Using
End Sub
<WpfFact, WorkItem(824331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824331"), WorkItem(820289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820289"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestPeekDefinitionWhenExtensionMethodFromMetadata()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C { void M() { int[] a; a.$$Distinct(); }</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"Enumerable [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"Enumerable [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("Distinct", StringComparison.Ordinal))
End Using
End Sub
<WpfFact, WorkItem(819660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819660"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestPeekDefinitionFromVisualBasicMetadataAsSource()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[<System.$$Serializable()>
Class AA
End Class
</Document>
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"SerializableAttribute [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"SerializableAttribute [{EditorFeaturesResources.from_metadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("New()", StringComparison.Ordinal)) ' Navigates to constructor
End Using
End Sub
<WpfFact, WorkItem(819602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819602"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestPeekDefinitionOnParamNameXmlDocComment()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
''' <param name="$$exePath"></param>
Public Sub ddd(ByVal {|Identifier:exePath|} As String)
End Sub
End Class
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
<WpfFact, WorkItem(820363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820363"), Trait(Traits.Feature, Traits.Features.Peek)>
Public Sub TestPeekDefinitionOnLinqVariable()
Using workspace = TestWorkspace.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Module M
Sub S()
Dim arr = {3, 4, 5}
Dim q = From i In arr Select {|Identifier:$$d|} = i.GetType
End Sub
End Module
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
<WpfFact>
<WorkItem(1091211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091211")>
Public Sub TestPeekAcrossProjectsInvolvingPortableReferences()
Dim workspaceDefinition =
<Workspace>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferencesPortable="true">
<Document>
namespace N
{
public class CSClass
{
public void {|Identifier:M|}(int i) { }
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true" CommonReferenceFacadeSystemRuntime="true">
<ProjectReference>CSharpAssembly</ProjectReference>
<Document>
Imports N
Public Class VBClass
Sub Test()
Dim x As New CSClass()
x.M$$(5)
End Sub
End Class
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceDefinition)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
Private Function GetPeekResultCollection(element As XElement) As PeekResultCollection
Using workspace = TestWorkspace.Create(element)
Return GetPeekResultCollection(workspace)
End Using
End Function
Private Function GetPeekResultCollection(workspace As TestWorkspace) As PeekResultCollection
Dim document = workspace.Documents.FirstOrDefault(Function(d) d.CursorPosition.HasValue)
If document Is Nothing Then
AssertEx.Fail("The test is missing a $$ in the workspace.")
End If
Dim textBuffer = document.GetTextBuffer()
Dim textView = document.GetTextView()
Dim peekableItemSource As New PeekableItemSource(textBuffer,
workspace.GetService(Of IPeekableItemFactory),
New MockPeekResultFactory(workspace.GetService(Of IPersistentSpanFactory)),
workspace.GetService(Of IMetadataAsSourceFileService),
workspace.GetService(Of IWaitIndicator))
Dim peekableSession As New Mock(Of IPeekSession)(MockBehavior.Strict)
Dim triggerPoint = New SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value)
peekableSession.Setup(Function(s) s.GetTriggerPoint(It.IsAny(Of ITextSnapshot))).Returns(triggerPoint)
peekableSession.SetupGet(Function(s) s.RelationshipName).Returns("IsDefinedBy")
Dim items As New List(Of IPeekableItem)
peekableItemSource.AugmentPeekSession(peekableSession.Object, items)
If Not items.Any Then
Return Nothing
End If
Dim peekResult As New PeekResultCollection(workspace)
Dim item = items.SingleOrDefault()
If item IsNot Nothing Then
Dim resultSource = item.GetOrCreateResultSource(PredefinedPeekRelationships.Definitions.Name)
resultSource.FindResults(PredefinedPeekRelationships.Definitions.Name,
peekResult,
CancellationToken.None,
New Mock(Of IFindPeekResultsCallback)(MockBehavior.Loose).Object)
End If
Return peekResult
End Function
Private Class MockPeekResultFactory
Implements IPeekResultFactory
Private ReadOnly _persistentSpanFactory As IPersistentSpanFactory
Public Sub New(persistentSpanFactory As IPersistentSpanFactory)
_persistentSpanFactory = persistentSpanFactory
End Sub
Public Function Create(displayInfo As IPeekResultDisplayInfo, browseAction As Action) As IExternallyBrowsablePeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, eoiSpan As Span, idPosition As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Dim documentResult As New Mock(Of IDocumentPeekResult)(MockBehavior.Strict)
documentResult.SetupGet(Function(d) d.DisplayInfo).Returns(displayInfo)
documentResult.SetupGet(Function(d) d.FilePath).Returns(filePath)
documentResult.SetupGet(Function(d) d.IdentifyingSpan).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive))
documentResult.SetupGet(Function(d) d.Span).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive))
documentResult.SetupGet(Function(d) d.IsReadOnly).Returns(isReadOnly)
Return documentResult.Object
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid, postNavigationCallback As Action(Of IPeekResult, Object, Object)) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
End Class
Private Class PeekResultCollection
Implements IPeekResultCollection
Public ReadOnly Items As New List(Of IPeekResult)
Private ReadOnly _workspace As TestWorkspace
Public Sub New(workspace As TestWorkspace)
_workspace = workspace
End Sub
Private ReadOnly Property Count As Integer Implements IPeekResultCollection.Count
Get
Return Items.Count
End Get
End Property
Default Public Property Item(index As Integer) As IPeekResult Implements IPeekResultCollection.Item
Get
Return Items(index)
End Get
Set(value As IPeekResult)
Throw New NotImplementedException()
End Set
End Property
Private Sub Add(peekResult As IPeekResult) Implements IPeekResultCollection.Add
Items.Add(peekResult)
End Sub
Private Sub Clear() Implements IPeekResultCollection.Clear
Throw New NotImplementedException()
End Sub
Private Sub Insert(index As Integer, peekResult As IPeekResult) Implements IPeekResultCollection.Insert
Throw New NotImplementedException()
End Sub
Private Sub Move(oldIndex As Integer, newIndex As Integer) Implements IPeekResultCollection.Move
Throw New NotImplementedException()
End Sub
Private Sub RemoveAt(index As Integer) Implements IPeekResultCollection.RemoveAt
Throw New NotImplementedException()
End Sub
Private Function Contains(peekResult As IPeekResult) As Boolean Implements IPeekResultCollection.Contains
Throw New NotImplementedException()
End Function
Private Function IndexOf(peekResult As IPeekResult, startAt As Integer) As Integer Implements IPeekResultCollection.IndexOf
Throw New NotImplementedException()
End Function
Private Function Remove(item As IPeekResult) As Boolean Implements IPeekResultCollection.Remove
Throw New NotImplementedException()
End Function
''' <summary>
''' Returns the text of the identifier line, starting at the identifier and ending at end of the line.
''' </summary>
''' <param name="index"></param>
''' <returns></returns>
Friend Function GetRemainingIdentifierLineTextOnDisk(index As Integer) As String
Dim documentResult = DirectCast(Items(index), IDocumentPeekResult)
Dim textBufferService = _workspace.GetService(Of ITextBufferFactoryService)
Dim buffer = textBufferService.CreateTextBuffer(New StreamReader(documentResult.FilePath), textBufferService.InertContentType)
Dim startLine As Integer
Dim startIndex As Integer
Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for metadata file.")
Dim line = buffer.CurrentSnapshot.GetLineFromLineNumber(startLine)
Return buffer.CurrentSnapshot.GetText(line.Start + startIndex, line.Length - startIndex)
End Function
Friend Sub AssertNavigatesToIdentifier(index As Integer, name As String)
Dim documentResult = DirectCast(Items(index), IDocumentPeekResult)
Dim document = _workspace.Documents.FirstOrDefault(Function(d) d.FilePath = documentResult.FilePath)
AssertEx.NotNull(document, "Peek didn't navigate to a document in source. Navigated to " + documentResult.FilePath + " instead.")
Dim startLine As Integer
Dim startIndex As Integer
Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for source file.")
Dim snapshot = document.GetTextBuffer().CurrentSnapshot
Dim expectedPosition = New SnapshotPoint(snapshot, document.AnnotatedSpans(name).Single().Start)
Dim actualPosition = snapshot.GetLineFromLineNumber(startLine).Start + startIndex
Assert.Equal(expectedPosition, actualPosition)
End Sub
End Class
End Class
End Namespace
|
mmitche/roslyn
|
src/EditorFeatures/Test2/Peek/PeekTests.vb
|
Visual Basic
|
apache-2.0
| 21,168
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.UseNullPropagation
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicUseNullPropagationCodeFixProvider
Inherits AbstractUseNullPropagationCodeFixProvider(Of
SyntaxKind,
ExpressionSyntax,
TernaryConditionalExpressionSyntax,
BinaryExpressionSyntax,
InvocationExpressionSyntax,
MemberAccessExpressionSyntax,
ConditionalAccessExpressionSyntax,
InvocationExpressionSyntax)
End Class
End Namespace
|
mmitche/roslyn
|
src/Features/VisualBasic/Portable/UseNullPropagation/VisualBasicUseNullPropagationCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 922
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework
Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers
Imports Microsoft.CodeAnalysis
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
Public Class VisualBasicProjectTests
<Fact()>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Public Sub RenameProjectUpdatesWorkspace()
Using environment = New TestEnvironment()
Dim project = CreateVisualBasicProject(environment, "Test")
Dim hierarchy = DirectCast(project.Hierarchy, MockHierarchy)
Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().Name, "Test")
hierarchy.RenameProject("Test2")
Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().Name, "Test2")
project.Disconnect()
End Using
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/VisualStudio/Core/Test/ProjectSystemShim/VisualBasicProjectTests.vb
|
Visual Basic
|
apache-2.0
| 1,264
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OnErrorStatements
''' <summary>
''' Recommends "GoTo" after "On Error"
''' </summary>
Friend Class GoToKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End If
Dim targetToken = context.TargetToken
If targetToken.Kind = SyntaxKind.ErrorKeyword AndAlso IsOnErrorStatement(targetToken.Parent) AndAlso Not context.IsInLambda Then
Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("GoTo",
VBFeaturesResources.GotoKeywordToolTip))
Else
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End If
End Function
End Class
End Namespace
|
KevinRansom/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/OnErrorStatements/GoToKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 1,483
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Partial Class LocalRewriter
Private Structure XmlLiteralFixupData
Public Structure LocalWithInitialization
Public ReadOnly Local As LocalSymbol
Public ReadOnly Initialization As BoundExpression
Public Sub New(local As LocalSymbol, initialization As BoundExpression)
Me.Local = local
Me.Initialization = initialization
End Sub
End Structure
Private _locals As ArrayBuilder(Of LocalWithInitialization)
Public Sub AddLocal(local As LocalSymbol, initialization As BoundExpression)
If Me._locals Is Nothing Then
Me._locals = ArrayBuilder(Of LocalWithInitialization).GetInstance
End If
Me._locals.Add(New LocalWithInitialization(local, initialization))
End Sub
Public ReadOnly Property IsEmpty As Boolean
Get
Return Me._locals Is Nothing
End Get
End Property
Public Function MaterializeAndFree() As ImmutableArray(Of LocalWithInitialization)
Debug.Assert(Not Me.IsEmpty)
Dim materialized = Me._locals.ToImmutableAndFree
Me._locals = Nothing
Return materialized
End Function
End Structure
End Class
End Namespace
|
bbarry/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_XmlLiteralFixupData.vb
|
Visual Basic
|
apache-2.0
| 1,914
|
Imports System.Data.SqlClient
Imports System.Data.Common
Imports SistFoncreagro.BussinessEntities
Public Class DetalleRequerimientoRepository : Inherits MasterDataAccess : Implements IDetalleRequerimientoRepository
Dim catalogoRepository As ICatalogoRepository
Dim unidadRepository As IUnidadMedidaRepository
Sub New()
catalogoRepository = New CatalogoRepository
unidadRepository = New UnidadMedidaRepository
End Sub
Public Sub EliminarDetalle(ByVal idDetalleRequerimiento As Integer) Implements IDetalleRequerimientoRepository.EliminarDetalle
Dim command As SqlCommand = MyBase.CreateSPCommand("DeleteDETALLEREQUERIMIENTO")
command.Parameters.AddWithValue("IdDetalleRequerimiento", idDetalleRequerimiento)
MyBase.ExecuteNonQuery(command)
End Sub
Public Function GetAllFromDetalleRequerimientoByEstadoByIdReq(ByVal idRequerimiento As Integer) As System.Collections.Generic.List(Of BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.GetAllFromDetalleRequerimientoByEstadoByIdReq
Dim command As SqlCommand =
MyBase.CreateSPCommand("GetAllFromDetalleRequerimientoByEstadoByIdReq")
command.Parameters.AddWithValue("IdRequerimiento", idRequerimiento)
Return SelectObjectFactoryDetalleRequerimiento(command)
End Function
Public Function GetAllFromDetalleRequerimientoByIdReq(ByVal idRequerimiento As Integer) As System.Collections.Generic.List(Of BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.GetAllFromDetalleRequerimientoByIdReq
Dim command As SqlCommand = MyBase.CreateSPCommand("GetAllFromDETALLERREQUERIMIENTOByID")
command.Parameters.AddWithValue("IdRequerimiento", idRequerimiento)
Return SelectObjectFactoryDetalleRequerimiento(command)
End Function
Public Function GetAllFromDetalleRequerimientoOrdenadoByIdReq(ByVal idRequerimiento As Integer) As System.Collections.Generic.List(Of BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.GetAllFromDetalleRequerimientoOrdenadoByIdReq
Dim command As SqlCommand = MyBase.CreateSPCommand("GetAllFromDetalleRequerimientoOrdenadoByIdReq")
command.Parameters.AddWithValue("IdRequerimiento", idRequerimiento)
Return SelectObjectFactoryDetalleRequerimiento(command)
End Function
Public Function GetDetalleRequerimientoByIdDetalleReq(ByVal idDetalleRequerimiento As Integer) As BussinessEntities.DetalleRequerimiento Implements IDetalleRequerimientoRepository.GetDetalleRequerimientoByIdDetalleReq
Dim command As SqlCommand = MyBase.CreateSPCommand("GetDetalleRequerimientoByIdDetalleRequerimiento")
command.Parameters.AddWithValue("IdDetalleRequerimiento", idDetalleRequerimiento)
Return SelectObjectFactoryDetalleRequerimiento(command).SingleOrDefault
End Function
Public Sub SaveDetalleRequerimiento(ByVal detalleRequerimiento As BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.SaveDetalleRequerimiento
Dim command As SqlCommand = MyBase.CreateSPCommand("SaveDETALLEREQUERIMIENTO")
command.Parameters.AddWithValue("IdRequerimiento", detalleRequerimiento.IdRequerimiento)
command.Parameters.AddWithValue("IdCatalogo", detalleRequerimiento.IdCatalogo)
command.Parameters.AddWithValue("IdCentroCosto", detalleRequerimiento.IdCentroCosto)
MyBase.ExecuteNonQuery(command)
End Sub
Public Sub UpdateDetalleRequerimiento(ByVal detalleRequerimiento As BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.UpdateDetalleRequerimiento
Dim command As SqlCommand = MyBase.CreateSPCommand("ActualizarDETALLEREQUERIMIENTO")
command.Parameters.AddWithValue("IdDetalleRequerimiento", detalleRequerimiento.IdDetalleRequerimiento)
command.Parameters.AddWithValue("IdUnidadMedida", detalleRequerimiento.IdUnidadMedida)
command.Parameters.AddWithValue("IdCentroCosto", detalleRequerimiento.IdCentroCosto)
command.Parameters.AddWithValue("Cantidad", detalleRequerimiento.Cantidad)
command.Parameters.AddWithValue("Afecto", detalleRequerimiento.AfectoIgv)
command.Parameters.AddWithValue("Observacion", detalleRequerimiento.observacion)
MyBase.ExecuteNonQuery(command)
End Sub
Public Sub UpdateDetalleRequerimiento1(ByVal detalleRequerimiento As System.Collections.Generic.List(Of BussinessEntities.DetalleRequerimiento)) Implements IDetalleRequerimientoRepository.UpdateDetalleRequerimiento1
For Each det As DetalleRequerimiento In detalleRequerimiento
UpdateDetalleRequerimiento(det)
Next
End Sub
Public Sub UpdateDetalleReq(ByVal detalleRequerimiento As BussinessEntities.DetalleRequerimiento) Implements IDetalleRequerimientoRepository.UpdateDetalleReq
Dim command As SqlCommand = MyBase.CreateSPCommand("ActualizarDetalleAprobado")
command.Parameters.AddWithValue("IdDetalleRequerimiento", detalleRequerimiento.IdDetalleRequerimiento)
command.Parameters.AddWithValue("Observacion", detalleRequerimiento.observacion)
command.Parameters.AddWithValue("Afecto", detalleRequerimiento.AfectoIgv)
MyBase.ExecuteNonQuery(command)
End Sub
Public Sub UpdateDetalleReq1(ByVal detalleRequerimiento As System.Collections.Generic.List(Of BussinessEntities.DetalleRequerimiento)) Implements IDetalleRequerimientoRepository.UpdateDetalleReq1
For Each det As DetalleRequerimiento In detalleRequerimiento
UpdateDetalleReq(det)
Next
End Sub
Private Function SelectObjectFactoryDetalleRequerimiento(ByVal command As SqlCommand) As List(Of DetalleRequerimiento)
Dim listaDetalleRequerimiento As New List(Of DetalleRequerimiento)
Using reader As SqlDataReader = MyBase.ExecuteReader(command)
While reader.Read()
Dim detalleRequerimiento As New DetalleRequerimiento()
With detalleRequerimiento
.IdDetalleRequerimiento = reader.GetInt32(0)
.IdRequerimiento = reader.GetInt32(1)
.IdCatalogo = reader.GetInt32(2)
.IdUnidadMedida = reader.GetInt32(3)
.Cantidad = reader.GetDecimal(5)
.PrecioCompra = reader.GetDecimal(6)
.AfectoIgv = reader.GetBoolean(7)
.IdCentroCosto = reader.GetInt32(8)
.Estado = reader.GetInt32(9)
End With
If Not reader.IsDBNull(4) Then
detalleRequerimiento.observacion = reader.GetString(4)
End If
detalleRequerimiento.cat = catalogoRepository.GetAllFromCatalogoByIdCatalogo(reader.GetInt32(2))
detalleRequerimiento.unidad = unidadRepository.GetAllFromUnidadMedidaByIdUnidadMedida(reader.GetInt32(3))
listaDetalleRequerimiento.Add(detalleRequerimiento)
End While
End Using
Return listaDetalleRequerimiento
End Function
Public Sub AnularItemDetalle(ByVal idDetalleRequerimiento As Integer, ByVal motivo As String) Implements IDetalleRequerimientoRepository.AnularItemDetalle
Dim command As SqlCommand = MyBase.CreateSPCommand("AnularItemRequerimiento")
command.Parameters.AddWithValue("IdDetalleRequerimiento", idDetalleRequerimiento)
command.Parameters.AddWithValue("Motivo", motivo)
MyBase.ExecuteNonQuery(command)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.DataAccess/DetalleRequerimientoRepository.vb
|
Visual Basic
|
mit
| 7,602
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fPedidos_Clientes_IKP"
'-------------------------------------------------------------------------------------------'
Partial Class fPedidos_Clientes_IKP
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim loConsulta As New StringBuilder()
loConsulta.AppendLine("SELECT Pedidos.Cod_Cli, ")
loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Nom_Cli ELSE ")
loConsulta.AppendLine(" (CASE WHEN (Pedidos.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE Pedidos.Nom_Cli END) END) AS Nom_Cli, ")
loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Rif ELSE ")
loConsulta.AppendLine(" (CASE WHEN (Pedidos.Rif = '') THEN Clientes.Rif ELSE Pedidos.Rif END) END) AS Rif, ")
loConsulta.AppendLine(" Clientes.Nit, ")
loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE ")
loConsulta.AppendLine(" (CASE WHEN (SUBSTRING(Pedidos.Dir_Fis,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE SUBSTRING(Pedidos.Dir_Fis,1, 200) END) END) AS Dir_Fis, ")
loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Telefonos ELSE ")
loConsulta.AppendLine(" (CASE WHEN (Pedidos.Telefonos = '') THEN Clientes.Telefonos ELSE Pedidos.Telefonos END) END) AS Telefonos, ")
loConsulta.AppendLine(" Clientes.Fax, ")
loConsulta.AppendLine(" Pedidos.Nom_Cli As Nom_Gen, ")
loConsulta.AppendLine(" Pedidos.Rif As Rif_Gen, ")
loConsulta.AppendLine(" Pedidos.Nit As Nit_Gen, ")
loConsulta.AppendLine(" Pedidos.Dir_Fis As Dir_Gen, ")
loConsulta.AppendLine(" Pedidos.Telefonos As Tel_Gen, ")
loConsulta.AppendLine(" Pedidos.Documento, ")
loConsulta.AppendLine(" Pedidos.Fec_Ini, ")
loConsulta.AppendLine(" Pedidos.Fec_Fin, ")
loConsulta.AppendLine(" Pedidos.Mon_Bru, ")
loConsulta.AppendLine(" Pedidos.Por_Des1, ")
loConsulta.AppendLine(" Pedidos.Por_Rec1, ")
loConsulta.AppendLine(" Pedidos.Mon_Des1, ")
loConsulta.AppendLine(" Pedidos.Mon_Rec1, ")
loConsulta.AppendLine(" Pedidos.Mon_Imp1, ")
loConsulta.AppendLine(" Pedidos.Dis_Imp, ")
loConsulta.AppendLine(" Pedidos.Por_Imp1, ")
loConsulta.AppendLine(" Pedidos.Mon_Net, ")
loConsulta.AppendLine(" Pedidos.Cod_For, ")
loConsulta.AppendLine(" SUBSTRING(Formas_Pagos.Nom_For,1,25) AS Nom_For, ")
loConsulta.AppendLine(" Pedidos.Cod_Ven, ")
loConsulta.AppendLine(" Pedidos.Comentario, ")
loConsulta.AppendLine(" Vendedores.Nom_Ven, ")
loConsulta.AppendLine(" Renglones_Pedidos.Cod_Art, ")
'loComandoSeleccionar.AppendLine(" Articulos.Nom_Art, ")
loConsulta.AppendLine(" CASE WHEN Articulos.Generico = 0 THEN Articulos.Nom_Art ")
loConsulta.AppendLine(" ELSE Renglones_Pedidos.Notas END AS Nom_Art, ")
loConsulta.AppendLine(" Renglones_Pedidos.Renglon, ")
loConsulta.AppendLine(" Renglones_Pedidos.Can_Art1, ")
loConsulta.AppendLine(" Renglones_Pedidos.Cod_Uni, ")
loConsulta.AppendLine(" Renglones_Pedidos.Precio1, ")
loConsulta.AppendLine(" Renglones_Pedidos.Mon_Net As Neto, ")
loConsulta.AppendLine(" Renglones_Pedidos.Por_Imp1 As Por_Imp, ")
loConsulta.AppendLine(" Renglones_Pedidos.Cod_Imp, ")
loConsulta.AppendLine(" Renglones_Pedidos.Mon_Imp1 As Impuesto, ")
loConsulta.AppendLine(" Sucursales.nom_suc AS Nombre_Empresa_Cliente, ")
loConsulta.AppendLine(" COALESCE(campos_propiedades.val_car, '') AS Rif_Empresa_Cliente, ")
loConsulta.AppendLine(" Sucursales.direccion AS Direccion_Empresa_Cliente, ")
loConsulta.AppendLine(" Sucursales.telefonos AS Telefono_Empresa_Cliente ")
loConsulta.AppendLine("FROM Pedidos ")
loConsulta.AppendLine(" JOIN Renglones_Pedidos ON Pedidos.Documento = Renglones_Pedidos.Documento")
loConsulta.AppendLine(" JOIN Clientes ON Pedidos.Cod_Cli = Clientes.Cod_Cli")
loConsulta.AppendLine(" JOIN Formas_Pagos ON Pedidos.Cod_For = Formas_Pagos.Cod_For")
loConsulta.AppendLine(" JOIN Vendedores ON Pedidos.Cod_Ven = Vendedores.Cod_Ven")
loConsulta.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Pedidos.Cod_Art")
loConsulta.AppendLine(" JOIN Sucursales ON Sucursales.cod_suc = Pedidos.cod_suc")
loConsulta.AppendLine(" LEFT JOIN campos_propiedades ON campos_propiedades.cod_reg = Sucursales.cod_suc")
loConsulta.AppendLine(" AND campos_propiedades.origen = 'Sucursales'")
loConsulta.AppendLine(" AND campos_propiedades.cod_pro = 'SUC-RIF'")
loConsulta.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loConsulta.AppendLine("")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString, "curReportes")
Dim lcXml As String = "<impuesto></impuesto>"
Dim lcPorcentajesImpuesto As String
Dim loImpuestos As New System.Xml.XmlDocument()
lcPorcentajesImpuesto = "("
'Recorre cada renglon de la tabla
For lnNumeroFila As Integer = 0 To laDatosReporte.Tables(0).Rows.Count - 1
lcXml = laDatosReporte.Tables(0).Rows(lnNumeroFila).Item("dis_imp")
If String.IsNullOrEmpty(lcXml.Trim()) Then
Continue For
End If
loImpuestos.LoadXml(lcXml)
'En cada renglón lee el contenido de la distribució de impuestos
For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto")
If lnNumeroFila = laDatosReporte.Tables(0).Rows.Count - 1 Then
If CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText)<> 0 Then
lcPorcentajesImpuesto = lcPorcentajesImpuesto & ", " & CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) & "%"
End If
End If
Next loImpuesto
Next lnNumeroFila
lcPorcentajesImpuesto = lcPorcentajesImpuesto & ")"
lcPorcentajesImpuesto = lcPorcentajesImpuesto.Replace("(,", "(")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fPedidos_Clientes_IKP", laDatosReporte)
lcPorcentajesImpuesto = lcPorcentajesImpuesto.Replace(".",",")
CType(loObjetoReporte.ReportDefinition.ReportObjects("Text1"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpuesto.ToString
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfPedidos_Clientes_IKP.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' RJG: 02/08/13: Codigo inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fPedidos_Clientes_IKP.aspx.vb
|
Visual Basic
|
mit
| 10,524
|
Imports System.Data
Partial Class rProveedores_pZona
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim lcComandoSelect As String
lcComandoSelect = "SELECT Proveedores.Cod_Pro, " _
& "Proveedores.Nom_Pro, " _
& "Zonas.Cod_Zon " _
& "FROM Proveedores, Zonas " _
& "WHERE Proveedores.Cod_Zon = Zonas.Cod_Zon " _
& " And Zonas.Cod_Zon between '" & cusAplicacion.goReportes.paParametrosIniciales(0) & "'" _
& " And '" & cusAplicacion.goReportes.paParametrosFinales(0) & "'" _
& " ORDER BY Cod_Pro"
Try
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(lcComandoSelect, "curReportes")
Me.crvrProveedores_pZona.ReportSource = cusAplicacion.goReportes.mCargarReporte("rProveedores_pZona", laDatosReporte)
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
End Class
|
kodeitsolutions/ef-reports
|
rProveedores_pZona.aspx.vb
|
Visual Basic
|
mit
| 1,381
|
Public Class Form4
Private cx As New NPIData(NPIConnect.AccountBS)
Private DT As DataTable
Private X As String
Private Compcode As String
Private AssetID As String
Private AssetNo As String
Private AssetSubNo As String
Private AssetName As String
Private RespCctr As String
Private Sub Form4_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AddHandler cmdExecute.Click, AddressOf cmdExecute_Click
AddHandler dtgMaster.DoubleClick, AddressOf dtgMaster_DoubleClick
AddHandler cmdPicAdd.Click, AddressOf cmdPicAdd_Click
AddHandler cmdSavepic.Click, AddressOf cmdPicSave_Click
cmdPicAdd.Enabled = False
cmdSavepic.Enabled = False
End Sub
Private Sub cmdExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim A As New System.Text.StringBuilder("")
If txtCompcode.Text = "" Then A.Append("%") Else A.Append(String.Format("{0:N0}", txtCompcode.Text).ToString().PadLeft(4, "0"))
A.Append("-")
If txtAssetno.Text = "" Then A.Append("%") Else A.Append(String.Format("{0:N0}", txtAssetno.Text).ToString().PadLeft(12, "0"))
A.Append("-")
If txtSubno.Text = "" Then A.Append("%") Else A.Append(String.Format("{0:N0}", txtSubno.Text).ToString().PadLeft(4, "0"))
AssetID = A.ToString
A.Remove(0, A.ToString.Count)
A.Append("%")
A.Append(txtAssetname.Text)
A.Append("%")
AssetName = A.ToString
A.Remove(0, A.ToString.Count)
A.Append("%")
A.Append(txtRespcctr.Text)
A.Append("%")
RespCctr = A.ToString
A.Remove(0, A.ToString.Count)
X = String.Format("Exec Accdb.dbo.Asset_master '{0}','{1}','{2}'", AssetID, AssetName, RespCctr)
DT = cx.GetdataTable(X)
dtgMaster.DataSource = DT.DefaultView
cx.GridToList(dtgMaster)
cmdPicAdd.Enabled = False
cmdSavepic.Enabled = False
End Sub
Private Sub dtgMaster_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dx As DataGridView = sender
Dim y As Integer = dx.CurrentCell.RowIndex
lblAssetNo.Text = dx.Item("massetid", y).Value
X = String.Format("Exec accdb.dbo.asset_picture_show '{0}'", lblAssetNo.Text)
Dim dt1 As DataTable = cx.GetdataTable(X)
Try
Dim dr As DataRow = dt1.Rows(0)
If IsDBNull(dr!massetpiclarge) Then
picAsset.Image = Nothing
Else
picAsset.Image = cx.BytesToImage(dr!massetpiclarge)
End If
Catch ex As Exception
picAsset.Image = Nothing
End Try
cmdPicAdd.Enabled = True
cmdSavepic.Enabled = True
End Sub
Private Sub cmdPicAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim cdl As New OpenFileDialog
Dim bmp As Bitmap
Dim bmppixel As Double
Dim pixcelctrl As Integer = 300000
cdl.Filter = "JPEG File|*.jpg|GIF File|*.gif|PNG File|*.png"
If cdl.ShowDialog = Windows.Forms.DialogResult.OK Then
bmp = Image.FromFile(cdl.FileName)
bmppixel = bmp.Height * bmp.Width
bmppixel = (bmppixel Mod pixcelctrl) / bmppixel
If bmppixel < 1 Then
bmppixel = 1 - bmppixel
Else
bmppixel = 1
End If
Dim newbmp As New Bitmap(CInt(bmp.Width * bmppixel), CInt(bmp.Height * bmppixel))
Dim gr_dest As Graphics = Graphics.FromImage(newbmp)
gr_dest.DrawImage(bmp, 0, 0, newbmp.Width + 1, newbmp.Height + 1)
picAsset.Image = newbmp
Dim cmd As OleDbCommand = cx.CommandCreate("Exec accdb.dbo.asset_picture_insert ?,?,?,?", "TPTD")
cmd.Parameters(0).Value = lblAssetNo.Text
cmd.Parameters(1).Value = cx.ImageToBytesJPG(picAsset.Image)
cmd.Parameters(2).Value = Uname
cmd.Parameters(3).Value = Now()
cx.Execute(cmd)
MsgBox("Finish")
cmdPicAdd.Enabled = False
End If
End Sub
Private Sub cmdPicSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Get the two images
Dim img1 As Image = picAsset.Image
Using sfd As SaveFileDialog = New SaveFileDialog
'Set the dialog's properties
With sfd
.FileName = String.Empty
.Filter = "Jpeg|*.jpeg"
.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
.Title = "Save Dual Images"
End With
'If the user decides to save...
If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
'Declare a new bitmap with the width being both image's widths added together
'And the height being the larger of the two images
Using b As Bitmap = New Bitmap(img1.Width, img1.Height)
'Declare a new instance of graphics from our bitmap
Using g As Graphics = Graphics.FromImage(b)
'Draw the first image on the left
g.DrawImage(img1, New Point(0, 0))
'Save the graphics
g.Save()
End Using
'Save the bitmap
b.Save(sfd.FileName, Imaging.ImageFormat.Jpeg)
End Using
End If
End Using
MsgBox("เสร็จแล้ว อยู่ใน D:\image")
End Sub
End Class
|
100dej/PlanningS
|
Form/900/Form4.vb
|
Visual Basic
|
mit
| 5,667
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.GeneratedCodeRecognition
Imports Microsoft.CodeAnalysis.GenerateType
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Notification
Imports Microsoft.CodeAnalysis.ProjectManagement
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GenerateType
Public Class GenerateTypeViewModelTests
Private Shared Assembly1_Name As String = "Assembly1"
Private Shared Test1_Name As String = "Test1"
Private Shared Submit_failed_unexceptedly As String = "Submit failed unexceptedly."
Private Shared Submit_passed_unexceptedly As String = "Submit passed unexceptedly. Submit should fail here"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeExistingFileCSharp()
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, "C#")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Foo", viewModel.TypeName)
Assert.Equal("Foo.cs", viewModel.FileName)
Assert.Equal(Assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(Test1_Name + ".cs", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeExistingFileVisualBasic()
Dim documentContentMarkup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim x As A.B.Foo$$ = Nothing
End Sub
End Module
Namespace A
Namespace B
End Namespace
End Namespace"]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, "Visual Basic")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Foo", viewModel.TypeName)
Assert.Equal("Foo.vb", viewModel.FileName)
Assert.Equal(Assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(Test1_Name + ".vb", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeNewFileBothLanguage()
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
' Feed a filename and check if the change is effective
viewModel.FileName = "Wow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.Equal("Wow.cs", viewModel.FileName)
viewModel.FileName = "Foo\Bar\Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(2, viewModel.Folders.Count)
Assert.Equal("Foo", viewModel.Folders(0))
Assert.Equal("Bar", viewModel.Folders(1))
viewModel.FileName = "\ name has space \ Foo \Bar\ Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(3, viewModel.Folders.Count)
Assert.Equal("name has space", viewModel.Folders(0))
Assert.Equal("Foo", viewModel.Folders(1))
Assert.Equal("Bar", viewModel.Folders(2))
' Set it to invalid identifier
viewModel.FileName = "w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
viewModel.FileName = "wow\w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
viewModel.FileName = "w?d\wdd"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeProjectChangeAndDependencyBothLanguage()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true">
<ProjectReference>CS1</ProjectReference>
</Project>
<Project Language="C#" AssemblyName="CS3" CommonReferences="true">
<ProjectReference>CS2</ProjectReference>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
<Document FilePath="Test3.vb"></Document>
</Project>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, "")
' Only 2 Projects can be selected because CS2 and CS3 will introduce cyclic dependency
Assert.Equal(2, viewModel.ProjectList.Count)
Assert.Equal(2, viewModel.DocumentList.Count)
viewModel.DocumentSelectIndex = 1
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.DocumentList)
' Check to see if the values are reset when there is a change in the project selection
viewModel.SelectedProject = projectToSelect
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(0, viewModel.DocumentSelectIndex)
Assert.Equal(1, viewModel.ProjectSelectIndex)
monitor.VerifyExpectations()
monitor.Detach()
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeDisableExistingFileForEmptyProject()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, "")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is disabled
Assert.Equal(0, viewModel.DocumentList.Count())
Assert.Equal(False, viewModel.IsExistingFileEnabled)
' Select the project CS1 which has documents
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is enabled
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(True, viewModel.IsExistingFileEnabled)
End Sub
<WorkItem(858815)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeAllowPublicAccessOnlyForGenerationIntoOtherProject()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, "")
viewModel.SelectedAccessibilityString = "Default"
' Check if the AccessKind List is enabled
Assert.Equal(True, viewModel.IsAccessListEnabled)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if access kind is set to Public and the AccessKind is set to be disabled
Assert.Equal(2, viewModel.AccessSelectIndex)
Assert.Equal(False, viewModel.IsAccessListEnabled)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if AccessKind list is enabled again
Assert.Equal(True, viewModel.IsAccessListEnabled)
End Sub
<WorkItem(858815)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeAllowClassTypeKindForAttribute_CSharp()
Dim documentContentMarkup = <Text><![CDATA[
[Foo$$]
class Program
{
static void Main(string[] args)
{
}
}]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("FooAttribute", viewModel.TypeName)
End Sub
<WorkItem(858815)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeAllowClassTypeKindForAttribute_VisualBasic()
Dim documentContentMarkup = <Text><![CDATA[
<Blah$$>
Class C
End Class]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
Assert.Equal("BlahAttribute", viewModel.TypeName)
End Sub
<WorkItem(861544)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithCapsAttribute_VisualBasic()
Dim documentContentMarkup = <Text><![CDATA[
<FooAttribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("FooAttribute", viewModel.TypeName)
End Sub
<WorkItem(861544)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithoutCapsAttribute_VisualBasic()
Dim documentContentMarkup = <Text><![CDATA[
<Fooattribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("FooattributeAttribute", viewModel.TypeName)
End Sub
<WorkItem(861544)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithCapsAttribute_CSharp()
Dim documentContentMarkup = <Text><![CDATA[
[FooAttribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("FooAttribute", viewModel.TypeName)
End Sub
<WorkItem(861544)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithoutCapsAttribute_CSharp()
Dim documentContentMarkup = <Text><![CDATA[
[Fooattribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("FooattributeAttribute", viewModel.TypeName)
End Sub
<WorkItem(861462)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeCheckOnlyPublic_CSharp_1()
Dim documentContentMarkup = <Text><![CDATA[
public class C : $$D
{
}]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.BaseList)
' Check if interface, class is present
Assert.Equal(2, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("interface", viewModel.KindList(1))
' Check if all Accessibility are present
Assert.Equal(3, viewModel.AccessList.Count)
End Sub
<WorkItem(861462)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeCheckOnlyPublic_CSharp_2()
Dim documentContentMarkup = <Text><![CDATA[
public interface CCC : $$DDD
{
}]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if interface, class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("interface", viewModel.KindList(0))
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("public", viewModel.AccessList(0))
End Sub
<WorkItem(861462)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeCheckOnlyPublic_VisualBasic_1()
Dim documentContentMarkup = <Text><![CDATA[
Public Class C
Implements $$D
End Class]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=False)
' Check if only Interface is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
Assert.Equal(3, viewModel.AccessList.Count)
End Sub
<WorkItem(861462)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeCheckOnlyPublic_VisualBasic_2()
Dim documentContentMarkup = <Text><![CDATA[
Public Class CC
Inherits $$DD
End Class]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Sub
<WorkItem(861462)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeCheckOnlyPublic_VisualBasic_3()
Dim documentContentMarkup = <Text><![CDATA[
Public Interface CCC
Inherits $$DDD
End Interface]]></Text>
Dim viewModel = GetViewModel(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Sub
<WorkItem(861362)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithModuleOption()
Dim workspaceXml = <Workspace>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test1.vb">
Module Program
Sub Main(args As String())
Dim s as A.$$B.C
End Sub
End Module
Namespace A
End Namespace </Document>
</Project>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true"/>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, "", typeKindvalue:=TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)
' Check if Module is present in addition to the normal options
Assert.Equal(3, viewModel.KindList.Count)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' C# does not have Module
Assert.Equal(2, viewModel.KindList.Count)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
Assert.Equal(3, viewModel.KindList.Count)
End Sub
<WorkItem(858826)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeFileExtensionUpdate()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
Foo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, "")
' Assert the current display
Assert.Equal(viewModel.FileName, "Foo.cs")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the new current display
Assert.Equal(viewModel.FileName, "Foo.vb")
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the display is back to the way it was before
Assert.Equal(viewModel.FileName, "Foo.cs")
' Set the name with vb extension
viewModel.FileName = "Foo.vb"
' On focus change,we trigger this method
viewModel.UpdateFileNameExtension()
' Assert that the filename changes accordingly
Assert.Equal(viewModel.FileName, "Foo.cs")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeExcludeGeneratedDocumentsFromList()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">$$</Document>
<Document FilePath="Test2.cs"></Document>
<Document FilePath="TemporaryGeneratedFile_test.cs"></Document>
<Document FilePath="AssemblyInfo.cs"></Document>
<Document FilePath="Test3.cs"></Document>
</Project>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, LanguageNames.CSharp)
Dim expectedDocuments = {"Test1.cs", "Test2.cs", "Test3.cs"}
Assert.Equal(expectedDocuments, viewModel.DocumentList.Select(Function(d) d.Document.Name).ToArray())
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeIntoGeneratedDocument()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test.generated.cs">
class Program
{
static void Main(string[] args)
{
Foo$$ bar;
}
}
</Document>
<Document FilePath="Test2.cs"></Document>
</Project>
</Workspace>
Dim viewModel = GetViewModel(workspaceXml, LanguageNames.CSharp)
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Foo", viewModel.TypeName)
Assert.Equal("Foo.cs", viewModel.FileName)
Assert.Equal("Test.generated.cs", viewModel.SelectedDocument.Name)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeNewFileNameOptions()
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true" FilePath="C:\A\B\CS1.csproj">
<Document FilePath="C:\A\B\CDE\F\Test1.cs">
class Program
{
static void Main(string[] args)
{
Foo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
<Document FilePath="C:\A\B\ExistingFile.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim projectFolder = PopulateProjectFolders(New List(Of String)(), "\outer\", "\outer\inner\")
Dim viewModel = GetViewModel(workspaceXml, "", projectFolders:=projectFolder)
viewModel.IsNewFile = True
' Assert the current display
Assert.Equal(viewModel.FileName, "Foo.cs")
' Set the folder to \outer\
viewModel.FileName = viewModel.ProjectFolders(0)
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename to \\something.cs
viewModel.FileName = "\\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename to an existing file
viewModel.FileName = "..\..\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename to empty
viewModel.FileName = " "
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename with more than permissible characters
viewModel.FileName = "sjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdfsjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdf.cs"
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename with keywords
viewModel.FileName = "com1\foo.cs"
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Set the Filename with ".."
viewModel.FileName = "..\..\foo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
' Set the Filename with ".."
viewModel.FileName = "..\.\..\.\foo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
End Sub
<WorkItem(898452)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeIntoNewFileWithInvalidIdentifierFolderName()
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = GetViewModel(documentContentMarkupCSharp, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
Dim foldersAreInvalid = "Folders are not valid identifiers"
viewModel.FileName = "123\456\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
Dim documentContentMarkupVB = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
viewModel = GetViewModel(documentContentMarkupVB, "Visual Basic", projectRootFilePath:="C:\OuterFolder1\InnerFolder1\")
viewModel.IsNewFile = True
viewModel.FileName = "123\456\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), Submit_failed_unexceptedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
End Sub
<WorkItem(898563)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateType_DontGenerateIntoExistingFile()
' Get a Temp Folder Path
Dim projectRootFolder = Path.GetTempPath()
' Get a random filename
Dim randomFileName = Path.GetRandomFileName()
' Get the final combined path of the file
Dim pathString = Path.Combine(projectRootFolder, randomFileName)
' Create the file
Dim fs = File.Create(pathString)
Dim bytearray = New Byte() {0, 1}
fs.Write(bytearray, 0, bytearray.Length)
fs.Close()
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Foo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = GetViewModel(documentContentMarkupCSharp, "C#", projectRootFilePath:=projectRootFolder)
viewModel.IsNewFile = True
viewModel.FileName = randomFileName
Assert.False(viewModel.TrySubmit(), Submit_passed_unexceptedly)
' Cleanup
File.Delete(pathString)
End Sub
Private Function PopulateProjectFolders(list As List(Of String), ParamArray values As String()) As List(Of String)
list.AddRange(values)
Return list
End Function
Private Function GetOneProjectWorkspace(
documentContent As XElement,
languageName As String,
projectName As String,
documentName As String,
projectRootFilePath As String) As XElement
Dim documentNameWithExtension = documentName + If(languageName = "C#", ".cs", ".vb")
If projectRootFilePath Is Nothing Then
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true">
<Document FilePath=<%= documentNameWithExtension %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
Else
Dim projectFilePath As String = projectRootFilePath + projectName + If(languageName = "C#", ".csproj", ".vbproj")
Dim documentFilePath As String = projectRootFilePath + documentNameWithExtension
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true" FilePath=<%= projectFilePath %>>
<Document FilePath=<%= documentFilePath %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
End If
End Function
Private Function GetViewModel(
content As XElement,
languageName As String,
Optional isNewFile As Boolean = False,
Optional accessSelectString As String = "",
Optional kindSelectString As String = "",
Optional projectName As String = "Assembly1",
Optional documentName As String = "Test1",
Optional typeKindvalue As TypeKindOptions = TypeKindOptions.AllOptions,
Optional isPublicOnlyAccessibility As Boolean = False,
Optional isAttribute As Boolean = False,
Optional projectFolders As List(Of String) = Nothing,
Optional projectRootFilePath As String = Nothing) As GenerateTypeDialogViewModel
Dim workspaceXml = If(content.Name.LocalName = "Workspace", content, GetOneProjectWorkspace(content, languageName, projectName, documentName, projectRootFilePath))
Using workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)
Dim testDoc = workspace.Documents.SingleOrDefault(Function(d) d.CursorPosition.HasValue)
Assert.NotNull(testDoc)
Dim document = workspace.CurrentSolution.GetDocument(testDoc.Id)
Dim token = document.GetSyntaxTreeAsync().Result.GetTouchingWord(testDoc.CursorPosition.Value, document.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim typeName = token.ToString()
Dim testProjectManagementService As IProjectManagementService = Nothing
If projectFolders IsNot Nothing Then
testProjectManagementService = New TestProjectManagementService(projectFolders)
End If
Dim syntaxFactsService = document.Project.LanguageServices.GetService(Of ISyntaxFactsService)()
Return New GenerateTypeDialogViewModel(
document,
New TestNotificationService(),
testProjectManagementService,
syntaxFactsService,
workspace.Services.GetService(Of IGeneratedCodeRecognitionService)(),
New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute),
typeName,
If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"),
isNewFile,
accessSelectString,
kindSelectString)
End Using
End Function
End Class
Friend Class TestProjectManagementService
Implements IProjectManagementService
Private projectFolders As List(Of String)
Public Sub New(projectFolders As List(Of String))
Me.projectFolders = projectFolders
End Sub
Public Function GetDefaultNamespace(project As Project, workspace As Workspace) As String Implements IProjectManagementService.GetDefaultNamespace
Return ""
End Function
Public Function GetFolders(projectId As ProjectId, workspace As Workspace) As IList(Of String) Implements IProjectManagementService.GetFolders
Return Me.projectFolders
End Function
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/VisualStudio/Core/Test/GenerateType/GenerateTypeViewModelTests.vb
|
Visual Basic
|
apache-2.0
| 37,159
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
void Bar(int i)
{
Console.WriteLine(i);
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
void Bar()
{
Foo([|i|]: 0);
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterCaseSensitivity1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
Console.WriteLine(I);
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterCaseSensitivity2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
sub Foo(byval {|Definition:$$i|} as Integer)
Console.WriteLine([|i|])
Console.WriteLine([|I|])
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(542475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542475")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPartialParameter1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class program
{
static partial void foo(string {|Definition:$$name|}, int age, bool sex, int index1 = 1) { }
}
partial class program
{
static partial void foo(string {|Definition:name|}, int age, bool sex, int index1 = 1);
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(542475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542475")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPartialParameter2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class program
{
static partial void foo(string {|Definition:name|}, int age, bool sex, int index1 = 1) { }
}
partial class program
{
static partial void foo(string {|Definition:$$name|}, int age, bool sex, int index1 = 1);
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
#Region "FAR on partial methods"
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameter_CSharpWithSignaturesMatchFARParameterOnDefDecl() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C
{
partial void PM(int {|Definition:$$x|}, int y);
partial void PM(int {|Definition:x|}, int y)
{
int s = [|x|];
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameter_VBWithSignaturesMatchFARParameterOnDefDecl() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
partial sub PM(x as Integer, y as Integer)
End Sub
partial sub PM({|Definition:x|} as Integer, y as Integer)
Dim y as Integer = [|$$x|];;
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
#End Region
<WorkItem(543276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543276")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main
Foo(Sub({|Definition:$$x|} As Integer) Return, Sub({|Definition:x|} As Integer) Return)
End Sub
Sub Foo(Of T)(x As T, y As T)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Dim field As Object = If(True, Function({|Definition:$$x|} As String) [|x|].ToUpper(), Function({|Definition:x|} As String) [|x|].ToLower())
End Module
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
public object O = true ? (Func<string, string>)((string {|Definition:$$x|}) => {return [|x|].ToUpper(); }) : (Func<string, string>)((string x) => {return x.ToLower(); });
}
]]>
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(543276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543276")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main
Foo(Sub({|Definition:x|} As Integer) Return, Sub({|Definition:$$x|} As Integer) Return)
End Sub
Sub Foo(Of T)(x As T, y As T)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter5() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Module M
Sub Main()
Dim s = Sub({|Definition:$$x|}) Return
s([|x|]:=1)
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545654")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestReducedExtensionNamedParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Module M
Sub Main()
Dim x As New Stack(Of String)
Dim y = x.Foo(0, $$[|defaultValue|]:="")
End Sub
<Extension>
Function Foo(x As Stack(Of String), index As Integer, {|Definition:defaultValue|} As String) As String
End Function
End Module
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545654")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestReducedExtensionNamedParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Module M
Sub Main()
Dim x As New Stack(Of String)
Dim y = x.Foo(0, [|defaultValue|]:="")
End Sub
<Extension>
Function Foo(x As Stack(Of String), index As Integer, {|Definition:$$defaultValue|} As String) As String
End Function
End Module
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = {|Definition:$$a|} => [|a|];
Converter<int, int> c = a => a;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = {|Definition:a|} => [|$$a|];
Converter<int, int> c = a => a;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = a => a;
Converter<int, int> c = {|Definition:$$a|} => [|a|];
}
}
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = a => a;
Converter<int, int> c = {|Definition:a|} => [|$$a|];
}
}
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function({|Definition:$$a|}) [|a|]
dim c as Converter(of integer, integer) = Function(a) a
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function({|Definition:a|}) [|$$a|]
dim c as Converter(of integer, integer) = Function(a) a
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function(a) a
dim c as Converter(of integer, integer) = Function({|Definition:$$a|}) [|a|]
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter4() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function(a) a
dim c as Converter(of integer, integer) = Function({|Definition:a|}) [|$$a|]
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAsync(input)
End Function
End Class
End Namespace
|
Shiney/roslyn
|
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ParameterSymbol.vb
|
Visual Basic
|
apache-2.0
| 15,952
|
'------------------------------------------------------------------------------
' <auto-generated>
' 此代码由工具生成。
' 运行时版本:4.0.30319.296
'
' 对此文件的更改可能会导致不正确的行为,并且如果
' 重新生成代码,这些更改将会丢失。
' </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 自动保存功能"
#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.DBCodeGenerator.My.MySettings
Get
Return Global.DBCodeGenerator.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
welljoe/code-sidelights
|
DBCodeGenerator/DBCodeGenerator/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,930
|
'------------------------------------------------------------------------------
' <auto-generated>
' 此代码由工具生成。
' 运行时版本:4.0.30319.18444
'
' 对此文件的更改可能会导致不正确的行为,并且如果
' 重新生成代码,这些更改将会丢失。
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'注意: 此文件是自动生成的;请不要直接修改它。 若要进行更改,
' 或者如果您在此文件中遇到生成错误,请转至项目设计器
' (转至“项目属性”或在解决方案资源管理器中双击“我的项目”节点),
' 然后在“应用程序”选项卡中进行更改。
'
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.WindowsApplication1.Main
End Sub
End Class
End Namespace
|
S2Lab/QuickText
|
QuickText/My Project/Application.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,538
|
' 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", ignoreTrivia:=False)
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
End Class
End Namespace
|
kelltrick/roslyn
|
src/EditorFeatures/VisualBasicTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.vb
|
Visual Basic
|
apache-2.0
| 7,373
|
Imports System
Imports NUnit.Framework
Imports MyGeneration.dOOdads
Namespace MyGeneration.dOOdads.Tests.SQL
<TestFixture()> _
Public Class SqlEOFFixture
Dim aggTest As AggregateTest = New AggregateTest
Dim nCounter As Integer = 0
<TestFixtureSetUp()> _
Public Sub Init()
TransactionMgr.ThreadTransactionMgrReset()
aggTest.ConnectionString = Connections.SQLConnection
End Sub
<SetUp()> _
Public Sub Init2()
nCounter = 0
aggTest.FlushData
End Sub
<Test()> _
Public Sub EOFWithNoLoad()
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(0, nCounter)
End Sub
<Test()> _
Public Sub EOFWithFalseLoad()
aggTest.Where.IsActive.Operator = WhereParameter.Operand.Equal
aggTest.Where.IsActive.Value = True
Dim wp As WhereParameter = aggTest.Where.TearOff.IsActive
wp.Operator = WhereParameter.Operand.Equal
wp.Value = False
aggTest.Query.Load
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(0, nCounter)
End Sub
<Test()> _
Public Sub EOFWithOneRow()
aggTest.Query.Top = 1
aggTest.Query.Load
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(aggTest.Query.Top, nCounter)
End Sub
<Test()> _
Public Sub EOFWithTwoRows()
aggTest.Query.Top = 2
aggTest.Query.Load
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(aggTest.Query.Top, nCounter)
End Sub
<Test()> _
Public Sub EOFWithLoadAll()
aggTest.LoadAll
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(aggTest.RowCount, nCounter)
End Sub
<Test()> _
Public Sub EOFWithFilter()
aggTest.LoadAll
aggTest.Filter = "DepartmentID = 3"
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(8, nCounter)
aggTest.Filter = ""
nCounter = 0
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(30, nCounter)
End Sub
<Test()> _
Public Sub EOFWithEmptyFilter()
aggTest.LoadAll
aggTest.Filter = "DepartmentID = 99"
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(0, nCounter)
aggTest.Filter = ""
nCounter = 0
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(30, nCounter)
End Sub
<Test()> _
Public Sub EOFWithSort()
aggTest.LoadAll
aggTest.Sort = "ID DESC"
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(30, nCounter)
aggTest.Sort = ""
nCounter = 0
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(30, nCounter)
End Sub
<Test()> _
Public Sub EOFWithGroupBy()
aggTest.Query.CountAll = True
aggTest.Query.AddResultColumn(AggregateTest.ColumnNames.DepartmentID)
aggTest.Query.AddGroupBy(AggregateTest.ColumnNames.DepartmentID)
aggTest.Query.Load
While Not aggTest.EOF AndAlso nCounter < 35
nCounter = nCounter + 1
aggTest.MoveNext
End While
Assert.AreEqual(7, nCounter)
End Sub
End Class
End Namespace
|
cafephin/mygeneration
|
src/doodads/Tests/VBNet/SQL/SqlEOFFixture.vb
|
Visual Basic
|
bsd-3-clause
| 3,728
|
' 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.Windows.Data
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Class StyleViewModel
Inherits AbstractOptionPreviewViewModel
#Region "Preview Text"
Private Shared s_fieldDeclarationPreviewTrue As String = "
Class C
Private capacity As Integer
Sub Method()
'//[
Me.capacity = 0
'//]
End Sub
End Class
"
Private Shared s_fieldDeclarationPreviewFalse As String = "
Class C
Private capacity As Integer
Sub Method()
'//[
capacity = 0
'//]
End Sub
End Class
"
Private Shared s_propertyDeclarationPreviewTrue As String = "
Class C
Public Property Id As Integer
Sub Method()
'//[
Me.Id = 0
'//]
End Sub
End Class
"
Private Shared s_propertyDeclarationPreviewFalse As String = "
Class C
Public Property Id As Integer
Sub Method()
'//[
Id = 0
'//]
End Sub
End Class
"
Private Shared s_methodDeclarationPreviewTrue As String = "
Class C
Sub Display()
'//[
Me.Display()
'//]
End Sub
End Class
"
Private Shared s_methodDeclarationPreviewFalse As String = "
Class C
Sub Display()
'//[
Display()
'//]
End Sub
End Class
"
Private Shared s_eventDeclarationPreviewTrue As String = "
Imports System
Class C
Public Event Elapsed As EventHandler
Sub Handler(sender As Object, args As EventArgs)
'//[
AddHandler Me.Elapsed, AddressOf Handler
'//]
End Sub
End Class
"
Private Shared s_eventDeclarationPreviewFalse As String = "
Imports System
Class C
Public Event Elapsed As EventHandler
Sub Handler(sender As Object, args As EventArgs)
'//[
AddHandler Elapsed, AddressOf Handler
'//]
End Sub
End Class
"
Private _intrinsicDeclarationPreviewTrue As String = <a><![CDATA[
Class Program
'//[
Private _member As Integer
Sub M(argument As Integer)
Dim local As Integer = 0
End Sub
'//]
End Class
]]></a>.Value
Private _intrinsicDeclarationPreviewFalse As String = <a><![CDATA[
Class Program
'//[
Private _member As Int32
Sub M(argument As Int32)
Dim local As Int32 = 0
End Sub
'//]
End Class
]]></a>.Value
Private _intrinsicMemberAccessPreviewTrue As String = <a><![CDATA[
Imports System
Class Program
'//[
Sub M()
Dim local = Integer.MaxValue
End Sub
'//]
End Class
]]></a>.Value
Private _intrinsicMemberAccessPreviewFalse As String = <a><![CDATA[
Imports System
Class Program
'//[
Sub M()
Dim local = Int32.MaxValue
End Sub
'//]
End Class
]]></a>.Value
Private Shared ReadOnly s_preferObjectInitializer As String = $"
Imports System
Class Customer
Private Age As Integer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim c = New Customer() With {{
.Age = 21
}}
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim c = New Customer()
c.Age = 21
//]
End Sub
End Class"
Private Shared ReadOnly s_preferCollectionInitializer As String = $"
Class Customer
Private Age As Integer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim list = New List(Of Integer) From {{
1,
2,
3
}}
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim list = New List(Of Integer)()
list.Add(1)
list.Add(2)
list.Add(3)
//]
End Sub
End Class"
Private Shared ReadOnly s_preferSimplifiedConditionalExpressions As String = $"
Class Customer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim x = A() AndAlso B()
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim x = If(A() AndAlso B(), True, False)
//]
End Sub
Function A() As Boolean
Return True
End Function
Function B() As Boolean
Return True
End Function
End Class"
Private Shared ReadOnly s_preferExplicitTupleName As String = $"
Class Customer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim customer As (name As String, age As Integer)
Dim name = customer.name
Dim age = customer.age
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim customer As (name As String, age As Integer)
Dim name = customer.Item1
Dim age = customer.Item2
//]
End Sub
end class
"
Private Shared ReadOnly s_preferInferredTupleName As String = $"
Class Customer
Sub M1(name as String, age As Integer)
//[
' {ServicesVSResources.Prefer_colon}
Dim tuple = (name, age)
//]
End Sub
Sub M2(name as String, age As Integer)
//[
' {ServicesVSResources.Over_colon}
Dim tuple = (name:=name, age:=age)
//]
End Sub
end class
"
Private Shared ReadOnly s_preferInferredAnonymousTypeMemberName As String = $"
Class Customer
Sub M1(name as String, age As Integer)
//[
' {ServicesVSResources.Prefer_colon}
Dim anon = New With {{ name, age }}
//]
End Sub
Sub M2(name as String, age As Integer)
//[
' {ServicesVSResources.Over_colon}
Dim anon = New With {{ .name = name, .age = age }}
//]
End Sub
end class
"
Private Shared ReadOnly s_preferConditionalExpressionOverIfWithAssignments As String = $"
Class Customer
Public Sub New(name as String, age As Integer)
//[
' {ServicesVSResources.Prefer_colon}
Dim s As String = If(expr, ""hello"", ""world"")
' {ServicesVSResources.Over_colon}
Dim s As String
If expr Then
s = ""hello""
Else
s = ""world""
End If
//]
End Sub
end class
"
Private Shared ReadOnly s_preferConditionalExpressionOverIfWithReturns As String = $"
Class Customer
Public Sub New(name as String, age As Integer)
//[
' {ServicesVSResources.Prefer_colon}
Return If(expr, ""hello"", ""world"")
' {ServicesVSResources.Over_colon}
If expr Then
Return ""hello""
Else
Return ""world""
End If
//]
End Sub
end class
"
Private Shared ReadOnly s_preferCoalesceExpression As String = $"
Imports System
Class Customer
Private Age As Integer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = If(x, y)
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim v = If(x Is Nothing, y, x) ' {ServicesVSResources.or}
Dim v = If(x IsNot Nothing, x, y)
//]
End Sub
End Class"
Private Shared ReadOnly s_preferNullPropagation As String = $"
Imports System
Class Customer
Private Age As Integer
Sub M1()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = o?.ToString()
//]
End Sub
Sub M2()
//[
' {ServicesVSResources.Over_colon}
Dim v = If(o Is Nothing, Nothing, o.ToString()) ' {ServicesVSResources.or}
Dim v = If(o IsNot Nothing, o.ToString(), Nothing)
//]
End Sub
End Class"
Private Shared ReadOnly s_preferAutoProperties As String = $"
Imports System
Class Customer1
//[
' {ServicesVSResources.Prefer_colon}
Public ReadOnly Property Age As Integer
//]
End Class
Class Customer2
//[
' {ServicesVSResources.Over_colon}
Private _age As Integer
Public ReadOnly Property Age As Integer
Get
return _age
End Get
End Property
//]
End Class
"
Private Shared ReadOnly s_preferSystemHashCode As String = $"
Imports System
Class Customer1
Dim a, b, c As Integer
//[
' {ServicesVSResources.Prefer_colon}
// {ServicesVSResources.Requires_System_HashCode_be_present_in_project}
Public Overrides Function GetHashCodeAsInteger()
Return System.HashCode.Combine(a, b, c)
End Function
//]
End Class
Class Customer2
Dim a, b, c As Integer
//[
' {ServicesVSResources.Over_colon}
Public Overrides Function GetHashCodeAsInteger()
Dim hashCode = 339610899
hashCode = hashCode * -1521134295 + a.GetHashCode()
hashCode = hashCode * -1521134295 + b.GetHashCode()
hashCode = hashCode * -1521134295 + c.GetHashCode()
return hashCode
End Function
//]
End Class
"
Private Shared ReadOnly s_preferIsNothingCheckOverReferenceEquals As String = $"
Imports System
Class Customer
Sub M1(value as object)
//[
' {ServicesVSResources.Prefer_colon}
If value Is Nothing
Return
End If
//]
End Sub
Sub M2(value as object)
//[
' {ServicesVSResources.Over_colon}
If Object.ReferenceEquals(value, Nothing)
Return
End If
//]
End Sub
End Class"
Private Shared ReadOnly s_preferCompoundAssignments As String = $"
Imports System
Class Customer
Sub M1(value as integer)
//[
' {ServicesVSResources.Prefer_colon}
value += 10
//]
End Sub
Sub M2(value as integer)
//[
' {ServicesVSResources.Over_colon}
value = value + 10
//]
End Sub
End Class"
#Region "arithmetic binary parentheses"
Private Shared ReadOnly s_arithmeticBinaryAlwaysForClarity As String = $"
class C
sub M()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = a + (b * c)
' {ServicesVSResources.Over_colon}
Dim v = a + b * c
//]
end sub
end class
"
Private Shared ReadOnly s_arithmeticBinaryNeverIfUnnecessary As String = $"
class C
sub M()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = a + b * c
' {ServicesVSResources.Over_colon}
Dim v = a + (b * c)
//]
end sub
end class
"
#End Region
#Region "relational binary parentheses"
Private Shared ReadOnly s_relationalBinaryAlwaysForClarity As String = $"
class C
sub M()
//[
' {ServicesVSResources.Keep_all_parentheses_in_colon}
Dim v = (a < b) = (c > d)
//]
end sub
end class
"
Private Shared ReadOnly s_relationalBinaryNeverIfUnnecessary As String = $"
class C
sub M()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = a < b = c > d
' {ServicesVSResources.Over_colon}
Dim v = (a < b) = (c > d)
//]
end sub
end class
"
#End Region
#Region "other binary parentheses"
Private ReadOnly s_otherBinaryAlwaysForClarity As String = $"
class C
sub M()
//[
// {ServicesVSResources.Prefer_colon}
Dim v = a OrElse (b AndAlso c)
// {ServicesVSResources.Over_colon}
Dim v = a OrElse b AndAlso c
//]
end sub
end class
"
Private ReadOnly s_otherBinaryNeverIfUnnecessary As String = $"
class C
sub M()
//[
// {ServicesVSResources.Prefer_colon}
Dim v = a OrElse b AndAlso c
// {ServicesVSResources.Over_colon}
Dim v = a OrElse (b AndAlso c)
//]
end sub
end class
"
#End Region
#Region "other parentheses"
Private Shared ReadOnly s_otherParenthesesAlwaysForClarity As String = $"
class C
sub M()
//[
' {ServicesVSResources.Keep_all_parentheses_in_colon}
Dim v = (a.b).Length
//]
end sub
end class
"
Private Shared ReadOnly s_otherParenthesesNeverIfUnnecessary As String = $"
class C
sub M()
//[
' {ServicesVSResources.Prefer_colon}
Dim v = a.b.Length
' {ServicesVSResources.Over_colon}
Dim v = (a.b).Length
//]
end sub
end class
"
#End Region
Private Shared ReadOnly s_preferReadonly As String = $"
Class Customer1
//[
' {ServicesVSResources.Prefer_colon}
' 'value' can only be assigned in constructor
Private ReadOnly value As Integer = 0
//]
End Class
Class Customer2
//[
' {ServicesVSResources.Over_colon}
' 'value' can be assigned anywhere
Private value As Integer = 0
//]
End Class"
#Region "unused parameters"
Private Shared ReadOnly s_avoidUnusedParametersNonPublicMethods As String = $"
Public Class C1
//[
' {ServicesVSResources.Prefer_colon}
Private Sub M()
End Sub
//]
End Class
Public Class C2
//[
' {ServicesVSResources.Over_colon}
Private Sub M(param As Integer)
End Sub
//]
End Class
"
Private Shared ReadOnly s_avoidUnusedParametersAllMethods As String = $"
Public Class C1
//[
' {ServicesVSResources.Prefer_colon}
Public Sub M()
End Sub
//]
End Class
Public Class C2
//[
' {ServicesVSResources.Over_colon}
Public Sub M(param As Integer)
End Sub
//]
End Class
"
#End Region
#Region "unused values"
Private Shared ReadOnly s_avoidUnusedValueAssignmentUnusedLocal As String = $"
Class C1
Function M() As Integer
//[
' {ServicesVSResources.Prefer_colon}
Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
Dim x = 1
//]
Return x
End Function
End Class
Class C2
Function M() As Integer
//[
' {ServicesVSResources.Over_colon}
Dim x = Computation() ' {ServicesVSResources.Value_assigned_here_is_never_used}
x = 1
//]
Return x
End Function
End Class
"
Private Shared ReadOnly s_avoidUnusedValueExpressionStatementUnusedLocal As String = $"
Class C1
Sub M()
//[
' {ServicesVSResources.Prefer_colon}
Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
//]
End Sub
End Class
Class C2
Sub M()
//[
' {ServicesVSResources.Over_colon}
Computation() ' {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored}
//]
End Sub
End Class
"
#End Region
#End Region
Public Sub New(optionStore As OptionStore, serviceProvider As IServiceProvider)
MyBase.New(optionStore, serviceProvider, LanguageNames.VisualBasic)
Dim collectionView = DirectCast(CollectionViewSource.GetDefaultView(CodeStyleItems), ListCollectionView)
collectionView.GroupDescriptions.Add(New PropertyGroupDescription(NameOf(AbstractCodeStyleOptionViewModel.GroupName)))
Dim qualifyGroupTitle = BasicVSResources.Me_preferences_colon
Dim qualifyMemberAccessPreferences = New List(Of CodeStylePreference) From
{
New CodeStylePreference(BasicVSResources.Prefer_Me, isChecked:=True),
New CodeStylePreference(BasicVSResources.Do_not_prefer_Me, isChecked:=False)
}
Dim predefinedTypesGroupTitle = BasicVSResources.Predefined_type_preferences_colon
Dim predefinedTypesPreferences = New List(Of CodeStylePreference) From
{
New CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked:=True),
New CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked:=False)
}
Dim codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon
Dim expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon
Dim nothingPreferencesGroupTitle = BasicVSResources.nothing_checking_colon
Dim fieldPreferencesGroupTitle = ServicesVSResources.Modifier_preferences_colon
Dim parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon
' qualify with Me. group
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, BasicVSResources.Qualify_field_access_with_Me, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, BasicVSResources.Qualify_property_access_with_Me, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, BasicVSResources.Qualify_method_access_with_Me, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, BasicVSResources.Qualify_event_access_with_Me, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences))
' predefined or framework type group
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, _intrinsicDeclarationPreviewTrue, _intrinsicDeclarationPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, _intrinsicMemberAccessPreviewTrue, _intrinsicMemberAccessPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences))
AddParenthesesOptions(optionStore)
' Code block
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, Me, optionStore, codeBlockPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, Me, optionStore, codeBlockPreferencesGroupTitle))
' expression preferences
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpressions, s_preferSimplifiedConditionalExpressions, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, Me, optionStore, expressionPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, Me, optionStore, expressionPreferencesGroupTitle))
AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle)
' nothing preferences
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, Me, optionStore, nothingPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, Me, optionStore, nothingPreferencesGroupTitle))
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, BasicVSResources.Prefer_Is_Nothing_for_reference_equality_checks, s_preferIsNothingCheckOverReferenceEquals, s_preferIsNothingCheckOverReferenceEquals, Me, optionStore, nothingPreferencesGroupTitle))
' Field preferences
Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, Me, optionStore, fieldPreferencesGroupTitle))
' Parameter preferences
AddParameterOptions(optionStore, parameterPreferencesGroupTitle)
End Sub
Private Sub AddParenthesesOptions(optionStore As OptionStore)
AddParenthesesOption(
LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses,
BasicVSResources.In_arithmetic_binary_operators,
{s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary},
defaultAddForClarity:=True)
AddParenthesesOption(
LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherBinaryParentheses,
BasicVSResources.In_other_binary_operators,
{s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary},
defaultAddForClarity:=True)
AddParenthesesOption(
LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.RelationalBinaryParentheses,
BasicVSResources.In_relational_binary_operators,
{s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary},
defaultAddForClarity:=True)
AddParenthesesOption(
LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherParentheses,
ServicesVSResources.In_other_operators,
{s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary},
defaultAddForClarity:=False)
End Sub
Private Sub AddUnusedValueOptions(optionStore As OptionStore, expressionPreferencesGroupTitle As String)
Dim unusedValuePreferences = New List(Of CodeStylePreference) From
{
New CodeStylePreference(BasicVSResources.Unused_local, isChecked:=True)
}
Dim enumValues =
{
UnusedValuePreference.UnusedLocalVariable
}
Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)(
VisualBasicCodeStyleOptions.UnusedValueAssignment,
ServicesVSResources.Avoid_unused_value_assignments,
enumValues,
{s_avoidUnusedValueAssignmentUnusedLocal},
Me,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences))
Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)(
VisualBasicCodeStyleOptions.UnusedValueExpressionStatement,
ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value,
enumValues,
{s_avoidUnusedValueExpressionStatementUnusedLocal},
Me,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences))
End Sub
Private Sub AddParameterOptions(optionStore As OptionStore, parameterPreferencesGroupTitle As String)
Dim examples =
{
s_avoidUnusedParametersNonPublicMethods,
s_avoidUnusedParametersAllMethods
}
AddUnusedParameterOption(LanguageNames.VisualBasic, optionStore, parameterPreferencesGroupTitle, examples)
End Sub
End Class
End Namespace
|
davkean/roslyn
|
src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb
|
Visual Basic
|
apache-2.0
| 26,196
|
' 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.Immutable
Imports System.Collections.ObjectModel
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend NotInheritable Class CompilationContext
Private Shared ReadOnly s_fullNameFormat As New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Friend Shared ReadOnly BackstopBinder As Binder = New BackstopBinder()
Friend ReadOnly Compilation As VisualBasicCompilation
Friend ReadOnly NamespaceBinder As Binder ' Internal for test purposes.
Private ReadOnly _metadataDecoder As MetadataDecoder
Private ReadOnly _currentFrame As MethodSymbol
Private ReadOnly _locals As ImmutableArray(Of LocalSymbol)
Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable)
Private ReadOnly _hoistedParameterNames As ImmutableHashSet(Of String)
Private ReadOnly _localsForBinding As ImmutableArray(Of LocalSymbol)
Private ReadOnly _syntax As ExecutableStatementSyntax
Private ReadOnly _methodNotType As Boolean
Private ReadOnly _voidType As NamedTypeSymbol
''' <summary>
''' Create a context to compile expressions within a method scope.
''' </summary>
Friend Sub New(
compilation As VisualBasicCompilation,
metadataDecoder As MetadataDecoder,
currentFrame As MethodSymbol,
locals As ImmutableArray(Of LocalSymbol),
inScopeHoistedLocals As InScopeHoistedLocals,
methodDebugInfo As MethodDebugInfo,
syntax As ExecutableStatementSyntax)
_syntax = syntax
_currentFrame = currentFrame
Debug.Assert(compilation.Options.RootNamespace = "") ' Default value.
Debug.Assert(methodDebugInfo.ExternAliasRecords.IsDefaultOrEmpty)
Dim originalCompilation = compilation
If syntax IsNot Nothing Then
compilation = compilation.AddSyntaxTrees(syntax.SyntaxTree)
End If
Dim defaultNamespaceName As String = methodDebugInfo.DefaultNamespaceName
If defaultNamespaceName IsNot Nothing Then
compilation = compilation.WithOptions(compilation.Options.WithRootNamespace(defaultNamespaceName))
End If
If compilation Is originalCompilation Then
compilation = compilation.Clone()
End If
Me.Compilation = compilation
' Each expression compile should use a unique compilation
' to ensure expression-specific synthesized members can be
' added (anonymous types, for instance).
Debug.Assert(Me.Compilation IsNot originalCompilation)
_metadataDecoder = metadataDecoder
NamespaceBinder = CreateBinderChain(
Me.Compilation,
metadataDecoder,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups)
_voidType = Me.Compilation.GetSpecialType(SpecialType.System_Void)
_methodNotType = Not locals.IsDefault
If _methodNotType Then
_locals = locals
Dim displayClassVariableNamesInOrder As ImmutableArray(Of String) = Nothing
GetDisplayClassVariables(currentFrame, locals, inScopeHoistedLocals, displayClassVariableNamesInOrder, _displayClassVariables, _hoistedParameterNames)
Debug.Assert(displayClassVariableNamesInOrder.Length = _displayClassVariables.Count)
_localsForBinding = GetLocalsForBinding(locals, displayClassVariableNamesInOrder, _displayClassVariables)
Else
_locals = ImmutableArray(Of LocalSymbol).Empty
_displayClassVariables = ImmutableDictionary(Of String, DisplayClassVariable).Empty
_localsForBinding = ImmutableArray(Of LocalSymbol).Empty
End If
' Assert that the cheap check for "Me" is equivalent to the expensive check for "Me".
Debug.Assert(
_displayClassVariables.ContainsKey(StringConstants.HoistedMeName) =
_displayClassVariables.Values.Any(Function(v) v.Kind = DisplayClassVariableKind.Me))
End Sub
Friend Function Compile(
typeName As String,
methodName As String,
aliases As ImmutableArray(Of [Alias]),
testData As Microsoft.CodeAnalysis.CodeGen.CompilationTestData,
diagnostics As DiagnosticBag,
<Out> ByRef resultProperties As ResultProperties) As CommonPEModuleBuilder
Dim properties As ResultProperties = Nothing
Dim objectType = Me.Compilation.GetSpecialType(SpecialType.System_Object)
Dim synthesizedType = New EENamedTypeSymbol(
Me.Compilation.SourceAssembly.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
Me,
Function(method, diags)
Dim hasDisplayClassMe = _displayClassVariables.ContainsKey(StringConstants.HoistedMeName)
Dim bindAsExpression = _syntax.Kind = SyntaxKind.PrintStatement
Dim binder = ExtendBinderChain(
aliases,
method,
NamespaceBinder,
hasDisplayClassMe,
_methodNotType,
allowImplicitDeclarations:=Not bindAsExpression)
Return If(bindAsExpression,
BindExpression(binder, DirectCast(_syntax, PrintStatementSyntax).Expression, diags, properties),
BindStatement(binder, _syntax, diags, properties))
End Function)
Dim moduleBuilder = CreateModuleBuilder(
Me.Compilation,
synthesizedType.Methods,
additionalTypes:=ImmutableArray.Create(DirectCast(synthesizedType, NamedTypeSymbol)),
testData:=testData,
diagnostics:=diagnostics)
Debug.Assert(moduleBuilder IsNot Nothing)
Me.Compilation.Compile(
moduleBuilder,
win32Resources:=Nothing,
xmlDocStream:=Nothing,
emittingPdb:=False,
diagnostics:=diagnostics,
filterOpt:=Nothing,
cancellationToken:=CancellationToken.None)
If diagnostics.HasAnyErrors() Then
resultProperties = Nothing
Return Nothing
End If
#If DEBUG Then
Dim m = synthesizedType.GetMembers()(0)
' Should be no name mangling since the caller provided explicit names.
Debug.Assert(m.ContainingType.MetadataName = typeName)
Debug.Assert(m.MetadataName = methodName)
#End If
resultProperties = properties
Return moduleBuilder
End Function
Private Shared Function GetNextMethodName(builder As ArrayBuilder(Of MethodSymbol)) As String
' NOTE: These names are consumed by Concord, so there's no native precedent.
Return String.Format("<>m{0}", builder.Count)
End Function
''' <summary>
''' Generate a class containing methods that represent
''' the set of arguments and locals at the current scope.
''' </summary>
Friend Function CompileGetLocals(
typeName As String,
localBuilder As ArrayBuilder(Of LocalAndMethod),
argumentsOnly As Boolean,
aliases As ImmutableArray(Of [Alias]),
testData As Microsoft.CodeAnalysis.CodeGen.CompilationTestData,
diagnostics As DiagnosticBag) As CommonPEModuleBuilder
Dim objectType = Me.Compilation.GetSpecialType(SpecialType.System_Object)
Dim allTypeParameters = GetAllTypeParameters(_currentFrame)
Dim additionalTypes = ArrayBuilder(Of NamedTypeSymbol).GetInstance()
Dim typeVariablesType As EENamedTypeSymbol = Nothing
If Not argumentsOnly AndAlso allTypeParameters.Length > 0 Then
' Generate a generic type with matching type parameters.
' A null instance of this type will be used to represent
' the "Type variables" local.
typeVariablesType = New EENamedTypeSymbol(
Me.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
Function(m, t)
Dim constructor As New EEConstructorSymbol(t)
constructor.SetParameters(ImmutableArray(Of ParameterSymbol).Empty)
Return ImmutableArray.Create(Of MethodSymbol)(constructor)
End Function,
allTypeParameters,
Function(t1, t2) allTypeParameters.SelectAsArray(Function(tp, i, t) DirectCast(New SimpleTypeParameterSymbol(t, i, tp.GetUnmangledName()), TypeParameterSymbol), t2))
additionalTypes.Add(typeVariablesType)
End If
Dim synthesizedType As New EENamedTypeSymbol(
Me.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
Function(m, container)
Dim methodBuilder = ArrayBuilder(Of MethodSymbol).GetInstance()
If Not argumentsOnly Then
If aliases.Length > 0 Then
' Pseudo-variables: $exception, $ReturnValue, etc.
Dim typeNameDecoder = New EETypeNameDecoder(Me.Compilation, DirectCast(_currentFrame.ContainingModule, PEModuleSymbol))
For Each [alias] As [Alias] In aliases
Dim methodName = GetNextMethodName(methodBuilder)
Dim syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken))
Dim local = PlaceholderLocalSymbol.Create(typeNameDecoder, _currentFrame, [alias])
Dim aliasMethod = Me.CreateMethod(
container,
methodName,
syntax,
Function(method, diags)
Dim expression = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type)
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function)
localBuilder.Add(MakeLocalAndMethod(local, methodName, If(local.IsReadOnly, DkmClrCompilationResultFlags.ReadOnlyResult, DkmClrCompilationResultFlags.None)))
methodBuilder.Add(aliasMethod)
Next
End If
' "Me" for non-shared methods that are not display class methods
' or display class methods where the display class contains "$VB$Me".
If Not m.IsShared AndAlso (Not m.ContainingType.IsClosureOrStateMachineType() OrElse _displayClassVariables.ContainsKey(GeneratedNames.MakeStateMachineCapturedMeName())) Then
Dim methodName = GetNextMethodName(methodBuilder)
Dim method = Me.GetMeMethod(container, methodName)
localBuilder.Add(New VisualBasicLocalAndMethod("Me", "Me", methodName, DkmClrCompilationResultFlags.None)) ' NOTE: writable in Dev11.
methodBuilder.Add(method)
End If
End If
' Hoisted method parameters (represented as locals in the EE).
If Not _hoistedParameterNames.IsEmpty Then
Dim localIndex As Integer = 0
For Each local In _localsForBinding
' Since we are showing hoisted method parameters first, the parameters may appear out of order
' in the Locals window if only some of the parameters are hoisted. This is consistent with the
' behavior of the old EE.
If _hoistedParameterNames.Contains(local.Name) Then
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local))
End If
localIndex += 1
Next
End If
' Method parameters (except those that have been hoisted).
Dim parameterIndex = If(m.IsShared, 0, 1)
For Each parameter In m.Parameters
Dim parameterName As String = parameter.Name
If Not _hoistedParameterNames.Contains(parameterName) AndAlso GeneratedNames.GetKind(parameterName) = GeneratedNameKind.None Then
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex)
End If
parameterIndex += 1
Next
If Not argumentsOnly Then
' Locals.
Dim localIndex As Integer = 0
For Each local In _localsForBinding
If Not _hoistedParameterNames.Contains(local.Name) Then
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local))
End If
localIndex += 1
Next
' "Type variables".
If typeVariablesType IsNot Nothing Then
Dim methodName = GetNextMethodName(methodBuilder)
Dim returnType = typeVariablesType.Construct(ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(allTypeParameters))
Dim method = Me.GetTypeVariableMethod(container, methodName, returnType)
localBuilder.Add(New VisualBasicLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
methodName,
DkmClrCompilationResultFlags.ReadOnlyResult))
methodBuilder.Add(method)
End If
End If
Return methodBuilder.ToImmutableAndFree()
End Function)
additionalTypes.Add(synthesizedType)
Dim moduleBuilder = CreateModuleBuilder(
Me.Compilation,
synthesizedType.Methods,
additionalTypes:=additionalTypes.ToImmutableAndFree(),
testData:=testData,
diagnostics:=diagnostics)
Debug.Assert(moduleBuilder IsNot Nothing)
Me.Compilation.Compile(
moduleBuilder,
win32Resources:=Nothing,
xmlDocStream:=Nothing,
emittingPdb:=False,
diagnostics:=diagnostics,
filterOpt:=Nothing,
cancellationToken:=CancellationToken.None)
Return If(diagnostics.HasAnyErrors(), Nothing, moduleBuilder)
End Function
Private Sub AppendLocalAndMethod(
localBuilder As ArrayBuilder(Of LocalAndMethod),
methodBuilder As ArrayBuilder(Of MethodSymbol),
local As LocalSymbol,
container As EENamedTypeSymbol,
localIndex As Integer,
resultFlags As DkmClrCompilationResultFlags)
Dim methodName = GetNextMethodName(methodBuilder)
Dim method = Me.GetLocalMethod(container, methodName, local.Name, localIndex)
localBuilder.Add(MakeLocalAndMethod(local, methodName, resultFlags))
methodBuilder.Add(method)
End Sub
Private Sub AppendParameterAndMethod(
localBuilder As ArrayBuilder(Of LocalAndMethod),
methodBuilder As ArrayBuilder(Of MethodSymbol),
parameter As ParameterSymbol,
container As EENamedTypeSymbol,
parameterIndex As Integer)
' Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
' the ResultProvider needs to be able to disambiguate cases Like "Me" And "[Me]",
' which it can't do correctly without semantic information.
Dim name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name)
Dim methodName = GetNextMethodName(methodBuilder)
Dim method = Me.GetParameterMethod(container, methodName, parameter.Name, parameterIndex)
localBuilder.Add(New VisualBasicLocalAndMethod(name, name, methodName, DkmClrCompilationResultFlags.None))
methodBuilder.Add(method)
End Sub
Private Shared Function MakeLocalAndMethod(local As LocalSymbol, methodName As String, flags As DkmClrCompilationResultFlags) As LocalAndMethod
' Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
' the ResultProvider needs to be able to disambiguate cases Like "Me" And "[Me]",
' which it can't do correctly without semantic information.
Dim escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name)
Dim displayName = If(TryCast(local, PlaceholderLocalSymbol)?.DisplayName, escapedName)
Return New VisualBasicLocalAndMethod(escapedName, displayName, methodName, flags)
End Function
Private Shared Function CreateModuleBuilder(
compilation As VisualBasicCompilation,
methods As ImmutableArray(Of MethodSymbol),
additionalTypes As ImmutableArray(Of NamedTypeSymbol),
testData As Microsoft.CodeAnalysis.CodeGen.CompilationTestData,
diagnostics As DiagnosticBag) As EEAssemblyBuilder
' Each assembly must have a unique name.
Dim emitOptions = New EmitOptions(outputNameOverride:=ExpressionCompilerUtilities.GenerateUniqueName())
Dim runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion()
Dim serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion)
Return New EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, testData)
End Function
Friend Function CreateMethod(
container As EENamedTypeSymbol,
methodName As String,
syntax As VisualBasicSyntaxNode,
generateMethodBody As GenerateMethodBody) As EEMethodSymbol
Return New EEMethodSymbol(
Compilation,
container,
methodName,
syntax.GetLocation(),
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
_voidType,
generateMethodBody)
End Function
Private Function GetLocalMethod(container As EENamedTypeSymbol, methodName As String, localName As String, localIndex As Integer) As EEMethodSymbol
Dim syntax = SyntaxFactory.IdentifierName(localName)
Return Me.CreateMethod(
container,
methodName,
syntax,
Function(method, diagnostics)
Dim local = method.LocalsForBinding(localIndex)
Dim expression = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type)
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function)
End Function
Private Function GetParameterMethod(container As EENamedTypeSymbol, methodName As String, parameterName As String, parameterIndex As Integer) As EEMethodSymbol
Dim syntax = SyntaxFactory.IdentifierName(parameterName)
Return Me.CreateMethod(
container,
methodName,
syntax,
Function(method, diagnostics)
Dim parameter = method.Parameters(parameterIndex)
Dim expression = New BoundParameter(syntax, parameter, isLValue:=False, type:=parameter.Type)
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function)
End Function
Private Function GetMeMethod(container As EENamedTypeSymbol, methodName As String) As EEMethodSymbol
Dim syntax = SyntaxFactory.MeExpression()
Return Me.CreateMethod(
container,
methodName,
syntax,
Function(method, diagnostics)
Dim expression = New BoundMeReference(syntax, GetNonClosureOrStateMachineContainer(container.SubstitutedSourceType))
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function)
End Function
Private Function GetTypeVariableMethod(container As EENamedTypeSymbol, methodName As String, typeVariablesType As NamedTypeSymbol) As EEMethodSymbol
Dim syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken))
Return Me.CreateMethod(
container,
methodName,
syntax,
Function(method, diagnostics)
Dim type = method.TypeMap.SubstituteNamedType(typeVariablesType)
Dim expression = New BoundObjectCreationExpression(syntax, type.InstanceConstructors(0), ImmutableArray(Of BoundExpression).Empty, Nothing, type)
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function)
End Function
Private Shared Function BindExpression(binder As Binder, syntax As ExpressionSyntax, diagnostics As DiagnosticBag, <Out> ByRef resultProperties As ResultProperties) As BoundStatement
Dim expression = binder.BindExpression(syntax, diagnostics)
Dim flags = DkmClrCompilationResultFlags.None
If Not IsAssignableExpression(binder, expression) Then
flags = flags Or DkmClrCompilationResultFlags.ReadOnlyResult
End If
If MayHaveSideEffectsVisitor.MayHaveSideEffects(expression) Then
flags = flags Or DkmClrCompilationResultFlags.PotentialSideEffect
End If
If IsStatement(expression) Then
expression = binder.ReclassifyInvocationExpressionAsStatement(expression, diagnostics)
Else
expression = binder.MakeRValue(expression, diagnostics)
End If
Select Case expression.Type.SpecialType
Case SpecialType.System_Void
Debug.Assert(expression.ConstantValueOpt Is Nothing)
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant:=False)
Return New BoundExpressionStatement(syntax, expression).MakeCompilerGenerated()
Case SpecialType.System_Boolean
flags = flags Or DkmClrCompilationResultFlags.BoolResult
End Select
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValueOpt IsNot Nothing)
Return New BoundReturnStatement(syntax, expression, Nothing, Nothing).MakeCompilerGenerated()
End Function
Private Shared Function IsAssignableExpression(binder As Binder, expression As BoundExpression) As Boolean
Dim diagnostics = DiagnosticBag.GetInstance()
Dim value = binder.ReclassifyAsValue(expression, diagnostics)
Dim result = False
If Binder.IsValidAssignmentTarget(value) AndAlso Not diagnostics.HasAnyErrors() Then
Dim isError = False
binder.AdjustAssignmentTarget(value.Syntax, value, diagnostics, isError)
Debug.Assert(isError = diagnostics.HasAnyErrors())
result = Not isError
End If
diagnostics.Free()
Return result
End Function
Private Shared Function IsStatement(expression As BoundExpression) As Boolean
Select Case expression.Kind
Case BoundKind.Call
Return IsCallStatement(DirectCast(expression, BoundCall))
Case BoundKind.ConditionalAccess
Dim [call] = TryCast(DirectCast(expression, BoundConditionalAccess).AccessExpression, BoundCall)
Return ([call] IsNot Nothing) AndAlso IsCallStatement([call])
Case Else
Return False
End Select
End Function
Private Shared Function IsCallStatement([call] As BoundCall) As Boolean
Return [call].Method.IsSub
End Function
Private Shared Function BindStatement(binder As Binder, syntax As StatementSyntax, diagnostics As DiagnosticBag, <Out> ByRef resultProperties As ResultProperties) As BoundStatement
resultProperties = New ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect Or DkmClrCompilationResultFlags.ReadOnlyResult)
Return binder.BindStatement(syntax, diagnostics).MakeCompilerGenerated()
End Function
Private Shared Function CreateBinderChain(
compilation As VisualBasicCompilation,
metadataDecoder As MetadataDecoder,
[namespace] As NamespaceSymbol,
importRecordGroups As ImmutableArray(Of ImmutableArray(Of ImportRecord))) As Binder
Dim binder = BackstopBinder
binder = New SuppressDiagnosticsBinder(binder)
binder = New IgnoreAccessibilityBinder(binder)
binder = New SourceModuleBinder(binder, DirectCast(compilation.Assembly.Modules(0), SourceModuleSymbol))
If Not importRecordGroups.IsDefault Then
binder = BuildImportedSymbolsBinder(binder, New NamespaceBinder(binder, compilation.GlobalNamespace), metadataDecoder, importRecordGroups)
End If
Dim stack = ArrayBuilder(Of String).GetInstance()
Dim containingNamespace = [namespace]
While containingNamespace IsNot Nothing
stack.Push(containingNamespace.Name)
containingNamespace = containingNamespace.ContainingNamespace
End While
' PERF: we used to call compilation.GetCompilationNamespace on every iteration,
' but that involved walking up to the global namesapce, which we have to do
' anyway. Instead, we'll inline the functionality into our own walk of the
' namespace chain.
[namespace] = compilation.GlobalNamespace
While stack.Count > 0
Dim namespaceName = stack.Pop()
If namespaceName.Length > 0 Then
' We're re-getting the namespace, rather than using the one containing
' the current frame method, because we want the merged namespace
[namespace] = [namespace].GetNestedNamespace(namespaceName)
Debug.Assert([namespace] IsNot Nothing,
"We worked backwards from symbols to names, but no symbol exists for name '" + namespaceName + "'")
Else
Debug.Assert([namespace] Is compilation.GlobalNamespace)
End If
binder = New NamespaceBinder(binder, [namespace])
End While
stack.Free()
Return binder
End Function
Private Shared Function ExtendBinderChain(
aliases As ImmutableArray(Of [Alias]),
method As EEMethodSymbol,
binder As Binder,
hasDisplayClassMe As Boolean,
methodNotType As Boolean,
allowImplicitDeclarations As Boolean) As Binder
Dim substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassMe)
Dim substitutedSourceType = substitutedSourceMethod.ContainingType
Dim stack = ArrayBuilder(Of NamedTypeSymbol).GetInstance()
Dim type = substitutedSourceType
While type IsNot Nothing
stack.Push(type)
type = type.ContainingType
End While
While stack.Count > 0
substitutedSourceType = stack.Pop()
binder = New EENamedTypeBinder(substitutedSourceType, binder)
End While
stack.Free()
If substitutedSourceMethod.Arity > 0 Then
binder = New MethodTypeParametersBinder(binder, substitutedSourceMethod.TypeArguments.SelectAsArray(Function(t) DirectCast(t, TypeParameterSymbol)))
End If
' The "Type Context" is used when binding DebuggerDisplayAttribute expressions.
' We have chosen to explicitly disallow pseudo variables in that scenario.
If methodNotType Then
' Method locals and parameters shadow pseudo-variables.
Dim typeNameDecoder = New EETypeNameDecoder(binder.Compilation, DirectCast(substitutedSourceMethod.ContainingModule, PEModuleSymbol))
binder = New PlaceholderLocalBinder(aliases, method, typeNameDecoder, allowImplicitDeclarations, binder)
End If
' Even if there are no parameters or locals, this has the effect of setting
' the containing member to the substituted source method.
binder = New ParametersAndLocalsBinder(binder, method, substitutedSourceMethod)
Return binder
End Function
Private Shared Function BuildImportedSymbolsBinder(
containingBinder As Binder,
importBinder As Binder,
metadataDecoder As MetadataDecoder,
importRecordGroups As ImmutableArray(Of ImmutableArray(Of ImportRecord))) As Binder
Dim projectLevelImportsBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition) = Nothing
Dim fileLevelImportsBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition) = Nothing
Dim projectLevelAliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing
Dim fileLevelAliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing
Dim projectLevelXmlImports As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing
Dim fileLevelXmlImports As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing
Debug.Assert(importRecordGroups.Length = 2) ' First project-level, then file-level.
Dim projectLevelImportRecords = importRecordGroups(0)
Dim fileLevelImportRecords = importRecordGroups(1)
' Use this to give the imports different positions
Dim position = 0
For Each importRecord As ImportRecord In projectLevelImportRecords
If AddImportForRecord(
importRecord,
importBinder,
metadataDecoder,
position,
projectLevelImportsBuilder,
projectLevelAliases,
projectLevelXmlImports) Then
position += 1
End If
Next
For Each importRecord As ImportRecord In fileLevelImportRecords
If AddImportForRecord(
importRecord,
importBinder,
metadataDecoder,
position,
fileLevelImportsBuilder,
fileLevelAliases,
fileLevelXmlImports) Then
position += 1
End If
Next
' BinderBuilder.CreateBinderForSourceFile creates separate binders for the project- and file-level
' imports. We'd do the same, but we don't have a SourceFileBinder to put in between and that
' violates some (very specific) assertions about the shape of the binder chain. Instead, we will
' manually resolve ties and then create a single set of binders.
Dim binder = containingBinder
Dim importsBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition)
If projectLevelImportsBuilder Is Nothing Then
importsBuilder = fileLevelImportsBuilder
ElseIf fileLevelImportsBuilder Is Nothing Then
importsBuilder = projectLevelImportsBuilder
Else
importsBuilder = fileLevelImportsBuilder
importsBuilder.AddRange(projectLevelImportsBuilder)
projectLevelImportsBuilder.Free()
End If
If importsBuilder IsNot Nothing Then
Dim [imports] As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = importsBuilder.ToImmutableAndFree()
binder = New TypesOfImportedNamespacesMembersBinder(binder, [imports])
binder = New ImportedTypesAndNamespacesMembersBinder(binder, [imports])
End If
Dim aliases = MergeAliases(projectLevelAliases, fileLevelAliases)
If aliases IsNot Nothing Then
binder = New ImportAliasesBinder(binder, aliases)
End If
Dim xmlImports = MergeAliases(projectLevelXmlImports, fileLevelXmlImports)
If xmlImports IsNot Nothing Then
binder = New XmlNamespaceImportsBinder(binder, xmlImports)
End If
Return binder
End Function
Private Shared Function AddImportForRecord(
importRecord As ImportRecord,
importBinder As Binder,
metadataDecoder As MetadataDecoder,
position As Integer,
ByRef importsBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition),
ByRef aliases As Dictionary(Of String, AliasAndImportsClausePosition),
ByRef xmlImports As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) As Boolean
Dim targetString = importRecord.TargetString
' NB: It appears that imports of generic types are not included in the PDB, so we never have to worry about parsing them.
' NB: Unlike in C# PDBs, the assembly name will not be present, so we have to just bind the string.
Dim targetSyntax As NameSyntax = Nothing
If Not String.IsNullOrEmpty(targetString) AndAlso ' CurrentNamespace may be an empty string, new-format types may be null.
importRecord.TargetKind <> ImportTargetKind.XmlNamespace AndAlso
Not TryParseDottedName(targetString, targetSyntax) Then
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{targetString}'")
Return False
End If
' Check for syntactically invalid aliases.
Dim [alias] = importRecord.Alias
If Not String.IsNullOrEmpty([alias]) Then
Dim aliasNameSyntax As NameSyntax = Nothing
If Not TryParseDottedName([alias], aliasNameSyntax) OrElse aliasNameSyntax.Kind <> SyntaxKind.IdentifierName Then
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{[alias]}'")
Return False
End If
End If
Select Case importRecord.TargetKind
Case ImportTargetKind.Type
Dim typeSymbol As TypeSymbol
Dim portableImportRecord = TryCast(importRecord, PortableImportRecord)
If portableImportRecord IsNot Nothing Then
typeSymbol = portableImportRecord.GetTargetType(metadataDecoder)
Debug.Assert(typeSymbol IsNot Nothing)
Else
Debug.Assert(importRecord.Alias Is Nothing) ' Represented as ImportTargetKind.NamespaceOrType in old-format PDBs.
Dim unusedDiagnostics = DiagnosticBag.GetInstance()
typeSymbol = importBinder.BindTypeSyntax(targetSyntax, unusedDiagnostics)
unusedDiagnostics.Free()
Debug.Assert(typeSymbol IsNot Nothing)
If typeSymbol.Kind = SymbolKind.ErrorType Then
' Type is unrecognized. The import may have been
' valid in the original source but unnecessary.
Return False ' Don't add anything for this import.
End If
End If
If [alias] IsNot Nothing Then
Dim aliasSymbol As New AliasSymbol(importBinder.Compilation, importBinder.ContainingNamespaceOrType, [alias], typeSymbol, NoLocation.Singleton)
If aliases Is Nothing Then
aliases = New Dictionary(Of String, AliasAndImportsClausePosition)()
End If
' There's no real syntax, so there's no real position. We'll give them separate numbers though.
aliases([alias]) = New AliasAndImportsClausePosition(aliasSymbol, position)
Else
If importsBuilder Is Nothing Then
importsBuilder = ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition).GetInstance()
End If
' There's no real syntax, so there's no real position. We'll give them separate numbers though.
importsBuilder.Add(New NamespaceOrTypeAndImportsClausePosition(typeSymbol, position))
End If
' Dev12 treats the current namespace the same as any other namespace (see ProcedureContext::LoadImportsAndDefaultNamespaceNormal).
' It seems pointless to add an import for the namespace in which we are binding expressions, but the native source gives
' the impression that other namespaces may take the same form in Everett PDBs.
Case ImportTargetKind.CurrentNamespace, ImportTargetKind.Namespace ' Unaliased namespace or type
If targetString = "" Then
Debug.Assert(importRecord.TargetKind = ImportTargetKind.CurrentNamespace) ' The current namespace can be empty.
Return False
End If
Dim unusedDiagnostics = DiagnosticBag.GetInstance()
Dim namespaceOrTypeSymbol = importBinder.BindNamespaceOrTypeSyntax(targetSyntax, unusedDiagnostics)
unusedDiagnostics.Free()
Debug.Assert(namespaceOrTypeSymbol IsNot Nothing)
If namespaceOrTypeSymbol.Kind = SymbolKind.ErrorType Then
' Namespace is unrecognized. The import may have been
' valid in the original source but unnecessary.
Return False ' Don't add anything for this import.
End If
If importsBuilder Is Nothing Then
importsBuilder = ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition).GetInstance()
End If
' There's no real syntax, so there's no real position. We'll give them separate numbers though.
importsBuilder.Add(New NamespaceOrTypeAndImportsClausePosition(namespaceOrTypeSymbol, position))
Case ImportTargetKind.NamespaceOrType ' Aliased namespace or type
Debug.Assert(TypeOf importRecord Is NativeImportRecord) ' Only happens when reading old-format PDBs
Dim unusedDiagnostics = DiagnosticBag.GetInstance()
Dim namespaceOrTypeSymbol = importBinder.BindNamespaceOrTypeSyntax(targetSyntax, unusedDiagnostics)
unusedDiagnostics.Free()
Debug.Assert(namespaceOrTypeSymbol IsNot Nothing)
If namespaceOrTypeSymbol.Kind = SymbolKind.ErrorType Then
' Type is unrecognized. The import may have been
' valid in the original source but unnecessary.
Return False ' Don't add anything for this import.
End If
Debug.Assert([alias] IsNot Nothing) ' Implied by TargetKind
Dim aliasSymbol As New AliasSymbol(importBinder.Compilation, importBinder.ContainingNamespaceOrType, [alias], namespaceOrTypeSymbol, NoLocation.Singleton)
If aliases Is Nothing Then
aliases = New Dictionary(Of String, AliasAndImportsClausePosition)()
End If
' There's no real syntax, so there's no real position. We'll give them separate numbers though.
aliases([alias]) = New AliasAndImportsClausePosition(aliasSymbol, position)
Case ImportTargetKind.XmlNamespace
If xmlImports Is Nothing Then
xmlImports = New Dictionary(Of String, XmlNamespaceAndImportsClausePosition)()
End If
' There's no real syntax, so there's no real position. We'll give them separate numbers though.
xmlImports(importRecord.Alias) = New XmlNamespaceAndImportsClausePosition(importRecord.TargetString, position)
Case ImportTargetKind.DefaultNamespace
' Processed ahead of time so that it can be incorporated into the compilation before
' constructing the binder chain.
Return False
Case ImportTargetKind.MethodToken ' forwarding
' One level of forwarding is pre-processed away, but invalid PDBs might contain
' chains. Just ignore them (as in Dev12).
Return False
Case ImportTargetKind.Defunct
Return False
Case ImportTargetKind.Assembly
' VB doesn't have extern aliases.
Throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind)
End Select
Return True
End Function
Private Shared Function MergeAliases(Of T)(projectLevel As Dictionary(Of String, T), fileLevel As Dictionary(Of String, T)) As Dictionary(Of String, T)
If projectLevel Is Nothing Then
Return fileLevel
ElseIf fileLevel Is Nothing Then
Return projectLevel
End If
' File-level aliases win.
For Each pair In projectLevel
Dim [alias] As String = pair.Key
If Not fileLevel.ContainsKey([alias]) Then
fileLevel.Add([alias], pair.Value)
End If
Next
Return fileLevel
End Function
Private Shared Function SelectAndInitializeCollection(Of T)(
scope As ImportScope,
ByRef projectLevelCollection As T,
ByRef fileLevelCollection As T,
initializeCollection As Func(Of T)) As T
If scope = ImportScope.Project Then
If projectLevelCollection Is Nothing Then
projectLevelCollection = initializeCollection()
End If
Return projectLevelCollection
Else
Debug.Assert(scope = ImportScope.File OrElse scope = ImportScope.Unspecified)
If fileLevelCollection Is Nothing Then
fileLevelCollection = initializeCollection()
End If
Return fileLevelCollection
End If
End Function
''' <summary>
''' We don't want to use the real scanner because we want to treat keywords as identifiers.
''' Since the inputs are so simple, we'll just do the scanning ourselves.
''' </summary>
Friend Shared Function TryParseDottedName(input As String, <Out> ByRef output As NameSyntax) As Boolean
Dim pooled = PooledStringBuilder.GetInstance()
Try
Dim builder = pooled.Builder
output = Nothing
For Each ch In input
If builder.Length = 0 Then
If Not SyntaxFacts.IsIdentifierStartCharacter(ch) Then
output = Nothing
Return False
End If
builder.Append(ch)
ElseIf ch = "."c Then
Dim identifierName = SyntaxFactory.IdentifierName(builder.ToString())
builder.Clear()
output = If(output Is Nothing,
DirectCast(identifierName, NameSyntax),
SyntaxFactory.QualifiedName(output, identifierName))
ElseIf SyntaxFacts.IsIdentifierPartCharacter(ch) Then
builder.Append(ch)
Else
output = Nothing
Return False
End If
Next
' There must be at least one character in the last identifier.
If builder.Length = 0 Then
output = Nothing
Return False
End If
Dim finalIdentifierName = SyntaxFactory.IdentifierName(builder.ToString())
output = If(output Is Nothing,
DirectCast(finalIdentifierName, NameSyntax),
SyntaxFactory.QualifiedName(output, finalIdentifierName))
Return True
Finally
pooled.Free()
End Try
End Function
Friend ReadOnly Property MessageProvider As CommonMessageProvider
Get
Return Me.Compilation.MessageProvider
End Get
End Property
Private Shared Function GetLocalsForBinding(
locals As ImmutableArray(Of LocalSymbol),
displayClassVariableNamesInOrder As ImmutableArray(Of String),
displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable)) As ImmutableArray(Of LocalSymbol)
Dim builder = ArrayBuilder(Of LocalSymbol).GetInstance()
For Each local In locals
Dim name = local.Name
If name IsNot Nothing AndAlso Not IsGeneratedLocalName(name) Then
builder.Add(local)
End If
Next
For Each variableName In displayClassVariableNamesInOrder
Dim variable = displayClassVariables(variableName)
Select Case variable.Kind
Case DisplayClassVariableKind.Local,
DisplayClassVariableKind.Parameter
Debug.Assert(Not IsGeneratedLocalName(variable.Name)) ' Established by GetDisplayClassVariables.
builder.Add(New EEDisplayClassFieldLocalSymbol(variable))
End Select
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' Return a mapping of captured variables (parameters, locals, and "Me") to locals.
''' The mapping is needed to expose the original local identifiers (those from source)
''' in the binder.
''' </summary>
Private Shared Sub GetDisplayClassVariables(
method As MethodSymbol,
locals As ImmutableArray(Of LocalSymbol),
inScopeHoistedLocals As InScopeHoistedLocals,
<Out> ByRef displayClassVariableNamesInOrder As ImmutableArray(Of String),
<Out> ByRef displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable),
<Out> ByRef hoistedParameterNames As ImmutableHashSet(Of String))
' Calculated the shortest paths from locals to instances of display classes.
' There should not be two instances of the same display class immediately
' within any particular method.
Dim displayClassTypes = PooledHashSet(Of NamedTypeSymbol).GetInstance()
Dim displayClassInstances = ArrayBuilder(Of DisplayClassInstanceAndFields).GetInstance()
' Add any display class instances from locals (these will contain any hoisted locals).
For Each local As LocalSymbol In locals
Dim localName = local.Name
If localName IsNot Nothing AndAlso IsDisplayClassInstanceLocalName(localName) Then
Dim instance As New DisplayClassInstanceFromLocal(DirectCast(local, EELocalSymbol))
displayClassTypes.Add(instance.Type)
displayClassInstances.Add(New DisplayClassInstanceAndFields(instance))
End If
Next
For Each parameter As ParameterSymbol In method.Parameters
If GeneratedNames.GetKind(parameter.Name) = GeneratedNameKind.TransparentIdentifier Then
Dim instance As New DisplayClassInstanceFromParameter(parameter)
displayClassTypes.Add(instance.Type)
displayClassInstances.Add(New DisplayClassInstanceAndFields(instance))
End If
Next
Dim containingType = method.ContainingType
Dim isIteratorOrAsyncMethod = False
If containingType.IsClosureOrStateMachineType() Then
If Not method.IsShared Then
' Add "Me" display class instance.
Dim instance As New DisplayClassInstanceFromParameter(method.MeParameter)
displayClassTypes.Add(instance.Type)
displayClassInstances.Add(New DisplayClassInstanceAndFields(instance))
End If
isIteratorOrAsyncMethod = containingType.IsStateMachineType()
End If
If displayClassInstances.Any() Then
' Find any additional display class instances breadth first.
Dim depth = 0
While GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0
depth += 1
End While
' The locals are the set of all fields from the display classes.
Dim displayClassVariableNamesInOrderBuilder = ArrayBuilder(Of String).GetInstance()
Dim displayClassVariablesBuilder = PooledDictionary(Of String, DisplayClassVariable).GetInstance()
Dim parameterNames = PooledHashSet(Of String).GetInstance()
If isIteratorOrAsyncMethod Then
Debug.Assert(containingType.IsClosureOrStateMachineType())
For Each field In containingType.GetMembers.OfType(Of FieldSymbol)()
' All iterator and async state machine fields in VB have mangled names.
' The ones beginning with "$VB$Local_" are the hoisted parameters.
Dim fieldName = field.Name
Dim parameterName As String = Nothing
If GeneratedNames.TryParseHoistedUserVariableName(fieldName, parameterName) Then
parameterNames.Add(parameterName)
End If
Next
Else
For Each parameter In method.Parameters
parameterNames.Add(parameter.Name)
Next
End If
Dim pooledHoistedParameterNames = PooledHashSet(Of String).GetInstance()
For Each instance In displayClassInstances
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocals,
instance,
pooledHoistedParameterNames)
Next
hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet()
pooledHoistedParameterNames.Free()
parameterNames.Free()
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree()
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary()
displayClassVariablesBuilder.Free()
Else
hoistedParameterNames = ImmutableHashSet(Of String).Empty
displayClassVariableNamesInOrder = ImmutableArray(Of String).Empty
displayClassVariables = ImmutableDictionary(Of String, DisplayClassVariable).Empty
End If
displayClassTypes.Free()
displayClassInstances.Free()
End Sub
Private Shared Function IsHoistedMeFieldName(fieldName As String) As Boolean
Return fieldName.Equals(StringConstants.HoistedMeName, StringComparison.Ordinal)
End Function
Private Shared Function IsLambdaMethodName(methodName As String) As Boolean
Return methodName.StartsWith(StringConstants.LambdaMethodNamePrefix, StringComparison.Ordinal)
End Function
''' <summary>
''' Test whether the name is for a local holding an instance of a display class.
''' </summary>
Private Shared Function IsDisplayClassInstanceLocalName(name As String) As Boolean
Debug.Assert(name IsNot Nothing) ' Verified by caller.
Return name.StartsWith(StringConstants.ClosureVariablePrefix, StringComparison.Ordinal)
End Function
''' <summary>
''' Test whether the name is for a field holding an instance of a display class
''' (i.e. a hoisted display class instance local).
''' </summary>
Private Shared Function IsDisplayClassInstanceFieldName(name As String) As Boolean
Debug.Assert(name IsNot Nothing) ' Verified by caller.
Return name.StartsWith(StringConstants.HoistedSpecialVariablePrefix & StringConstants.ClosureVariablePrefix, StringComparison.Ordinal) OrElse
name.StartsWith(StringConstants.StateMachineHoistedUserVariablePrefix & StringConstants.ClosureVariablePrefix, StringComparison.Ordinal) OrElse
name.StartsWith(StringConstants.HoistedSpecialVariablePrefix & StringConstants.DisplayClassPrefix, StringComparison.Ordinal) ' Async lambda case
End Function
Private Shared Function IsTransparentIdentifierField(field As FieldSymbol) As Boolean
Dim fieldName = field.Name
Dim unmangledName As String = Nothing
If GeneratedNames.TryParseHoistedUserVariableName(fieldName, unmangledName) Then
fieldName = unmangledName
ElseIf field.IsAnonymousTypeField(unmangledName) Then
fieldName = unmangledName
End If
Return GeneratedNames.GetKind(fieldName) = GeneratedNameKind.TransparentIdentifier
End Function
Private Shared Function IsGeneratedLocalName(name As String) As Boolean
Debug.Assert(name IsNot Nothing) ' Verified by caller.
' If a local's name contains "$", then it is a generated local.
Return name.IndexOf("$"c) >= 0
End Function
Private Shared Function GetLocalResultFlags(local As LocalSymbol) As DkmClrCompilationResultFlags
Debug.Assert(local.IsConst OrElse Not local.IsReadOnly, "Didn't expect user-referenceable read-only local.")
Return If(
local.IsConst,
DkmClrCompilationResultFlags.ReadOnlyResult,
DkmClrCompilationResultFlags.None)
End Function
''' <summary>
''' Return the set of display class instances that can be reached from the given local.
''' A particular display class may be reachable from multiple locals. In those cases,
''' the instance from the shortest path (fewest intermediate fields) is returned.
''' </summary>
Private Shared Function GetDisplayClassInstances(
displayClassTypes As HashSet(Of NamedTypeSymbol),
displayClassInstances As ArrayBuilder(Of DisplayClassInstanceAndFields),
depth As Integer) As Integer
Debug.Assert(displayClassInstances.All(Function(p) p.Depth <= depth))
Dim atDepth = ArrayBuilder(Of DisplayClassInstanceAndFields).GetInstance()
atDepth.AddRange(displayClassInstances.Where(Function(p) p.Depth = depth))
Debug.Assert(atDepth.Count > 0)
Dim n = 0
For Each instance In atDepth
n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance)
Next
atDepth.Free()
Return n
End Function
Private Shared Function GetDisplayClassInstances(
displayClassTypes As HashSet(Of NamedTypeSymbol),
displayClassInstances As ArrayBuilder(Of DisplayClassInstanceAndFields),
instance As DisplayClassInstanceAndFields) As Integer
' Display class instance. The display class fields are variables.
Dim n = 0
For Each member In instance.Type.GetMembers()
If member.Kind <> SymbolKind.Field Then
Continue For
End If
Dim field = DirectCast(member, FieldSymbol)
Dim fieldType = field.Type
Dim fieldName As String = field.Name
If IsDisplayClassInstanceFieldName(fieldName) OrElse
IsTransparentIdentifierField(field) Then
Debug.Assert(Not field.IsShared)
' A local that is itself a display class instance.
If displayClassTypes.Add(DirectCast(fieldType, NamedTypeSymbol)) Then
Dim other = instance.FromField(field)
displayClassInstances.Add(other)
n += 1
End If
End If
Next
Return n
End Function
Private Shared Sub GetDisplayClassVariables(
displayClassVariableNamesInOrder As ArrayBuilder(Of String),
displayClassVariablesBuilder As Dictionary(Of String, DisplayClassVariable),
parameterNames As HashSet(Of String),
inScopeHoistedLocals As InScopeHoistedLocals,
instance As DisplayClassInstanceAndFields,
hoistedParameterNames As HashSet(Of String))
' Display class instance. The display class fields are variables.
For Each member In instance.Type.GetMembers()
If member.Kind <> SymbolKind.Field Then
Continue For
End If
Dim field = DirectCast(member, FieldSymbol)
Dim fieldName = field.Name
Dim unmangledName As String = Nothing
If field.IsAnonymousTypeField(unmangledName) Then
fieldName = unmangledName
End If
Dim variableKind As DisplayClassVariableKind
Dim variableName As String
If fieldName.StartsWith(StringConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then
Debug.Assert(Not field.IsShared)
variableKind = DisplayClassVariableKind.Local
variableName = fieldName.Substring(StringConstants.HoistedUserVariablePrefix.Length)
ElseIf fieldName.StartsWith(StringConstants.HoistedSpecialVariablePrefix, StringComparison.Ordinal) Then
Debug.Assert(Not field.IsShared)
variableKind = DisplayClassVariableKind.Local
variableName = fieldName.Substring(StringConstants.HoistedSpecialVariablePrefix.Length)
ElseIf fieldName.StartsWith(StringConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then
Debug.Assert(Not field.IsShared)
variableKind = DisplayClassVariableKind.Local
variableName = Nothing
Dim unusedIndex As Integer = Nothing
If Not inScopeHoistedLocals.IsInScope(fieldName) OrElse Not GeneratedNames.TryParseStateMachineHoistedUserVariableName(fieldName, variableName, unusedIndex) Then
Continue For
End If
ElseIf IsHoistedMeFieldName(fieldName) Then
Debug.Assert(Not field.IsShared)
' A reference to "Me".
variableKind = DisplayClassVariableKind.Me
variableName = fieldName ' As in C#, we retain the mangled name. It shouldn't be used, other than as a dictionary key.
ElseIf fieldName.StartsWith(StringConstants.LambdaCacheFieldPrefix, StringComparison.Ordinal) Then
Continue For
ElseIf GeneratedNames.GetKind(fieldName) = GeneratedNameKind.TransparentIdentifier
' A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(Not field.IsShared)
Continue For
Else
variableKind = DisplayClassVariableKind.Local
variableName = fieldName
End If
If variableKind <> DisplayClassVariableKind.Me AndAlso IsGeneratedLocalName(variableName) Then
Continue For
End If
If variableKind = DisplayClassVariableKind.Local AndAlso parameterNames.Contains(variableName) Then
variableKind = DisplayClassVariableKind.Parameter
hoistedParameterNames.Add(variableName)
End If
If displayClassVariablesBuilder.ContainsKey(variableName) Then
' Only expecting duplicates for async state machine
' fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder(variableName).DisplayClassFields.Count() = 1)
Debug.Assert(instance.Fields.Count() >= 1) ' greater depth
' There are two ways names could collide:
' 1) hoisted state machine locals in different scopes
' 2) hoisted state machine parameters that are also captured by lambdas
' The former should be impossible since we dropped out-of-scope hoisted
' locals above. We assert that we are seeing the latter.
Debug.Assert((variableKind = DisplayClassVariableKind.Parameter) OrElse
(variableKind = DisplayClassVariableKind.Me))
Else
displayClassVariableNamesInOrder.Add(variableName)
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field))
End If
Next
End Sub
''' <summary>
''' Identifies the method in which binding should occur.
''' </summary>
''' <param name="candidateSubstitutedSourceMethod">
''' The symbol of the method that is currently on top of the callstack, with
''' EE type parameters substituted in place of the original type parameters.
''' </param>
''' <param name="sourceMethodMustBeInstance">
''' True if "Me" is available via a display class in the current context
''' </param>
''' <returns>
''' If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
''' then we will attempt to determine which user-derived method caused it to be
''' generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
''' is a state machine MoveNext method, then we will try to find the iterator or
''' async method for which it was generated. if we are able to find the original
''' method, then we will substitue in the EE type parameters. Otherwise, we will
''' return <paramref name="candidateSubstitutedSourceMethod"/>.
''' </returns>
''' <remarks>
''' In the event that the original method is overloaded, we may not be able to determine
''' which overload actually corresponds to the state machine. In particular, we do not
''' have information about the signature of the original method (i.e. number of parameters,
''' parameter types and ref-kinds, return type). However, we conjecture that this
''' level of uncertainty is acceptable, since parameters are managed by a separate binder
''' in the synthesized binder chain and we have enough information to check the other method
''' properties that are used during binding (e.g. static-ness, generic arity, type parameter
''' constraints).
''' </remarks>
Friend Shared Function GetSubstitutedSourceMethod(
candidateSubstitutedSourceMethod As MethodSymbol,
sourceMethodMustBeInstance As Boolean) As MethodSymbol
Dim candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType
Dim candidateSourceTypeName = candidateSubstitutedSourceType.Name
Dim desiredMethodName As String = Nothing
If IsLambdaMethodName(candidateSubstitutedSourceMethod.Name) OrElse
GeneratedNames.TryParseStateMachineTypeName(candidateSourceTypeName, desiredMethodName) Then
' We could be in the MoveNext method of an async lambda. If that is the case, we can't
' figure out desiredMethodName by unmangling the name.
If desiredMethodName IsNot Nothing AndAlso IsLambdaMethodName(desiredMethodName) Then
desiredMethodName = Nothing
Dim containing = candidateSubstitutedSourceType.ContainingType
Debug.Assert(containing IsNot Nothing)
If containing.IsClosureType() Then
candidateSubstitutedSourceType = containing
sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Contains(StringConstants.HoistedMeName, StringComparer.Ordinal)
End If
End If
Dim desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters
' Type containing the original iterator, async, or lambda-containing method.
Dim substitutedSourceType = GetNonClosureOrStateMachineContainer(candidateSubstitutedSourceType)
For Each candidateMethod In substitutedSourceType.GetMembers().OfType(Of MethodSymbol)()
If IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance) Then
Return If(desiredTypeParameters.Length = 0,
candidateMethod,
candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments))
End If
Next
Debug.Assert(False, String.Format("Why didn't we find a substituted source method for {0}?", candidateSubstitutedSourceMethod))
End If
Return candidateSubstitutedSourceMethod
End Function
Private Shared Function GetNonClosureOrStateMachineContainer(type As NamedTypeSymbol) As NamedTypeSymbol
' 1) Display class and state machine types are always nested within the types
' that use them so that they can access private members of those types).
' 2) The native compiler used to produce nested display classes for nested lambdas,
' so we may have to walk out more than one level.
While type.IsClosureOrStateMachineType()
type = type.ContainingType
End While
Debug.Assert(type IsNot Nothing)
Return type
End Function
Private Shared Function IsViableSourceMethod(
candidateMethod As MethodSymbol,
desiredMethodName As String,
desiredTypeParameters As ImmutableArray(Of TypeParameterSymbol),
desiredMethodMustBeInstance As Boolean) As Boolean
Return _
Not candidateMethod.IsMustOverride AndAlso
(Not (desiredMethodMustBeInstance AndAlso candidateMethod.IsShared)) AndAlso
(desiredMethodName Is Nothing OrElse desiredMethodName = candidateMethod.Name) AndAlso
HasDesiredConstraints(candidateMethod, desiredTypeParameters)
End Function
Private Shared Function HasDesiredConstraints(candidateMethod As MethodSymbol, desiredTypeParameters As ImmutableArray(Of TypeParameterSymbol)) As Boolean
Dim arity = candidateMethod.Arity
If arity <> desiredTypeParameters.Length Then
Return False
ElseIf arity = 0 Then
Return True
End If
Dim indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity).As(Of TypeSymbol)
' NOTE: Can't seem to construct a type map for just the method type parameters,
' so we also specify a trivial map for the type parameters of the (immediately)
' containing type.
Dim candidateMethodDefinition As MethodSymbol = candidateMethod.OriginalDefinition
Dim sourceTypeTypeParameters As ImmutableArray(Of TypeParameterSymbol) = candidateMethodDefinition.ContainingType.TypeParameters
Dim candidateTypeMap = TypeSubstitution.Create(
candidateMethodDefinition,
sourceTypeTypeParameters.Concat(candidateMethodDefinition.TypeParameters),
sourceTypeTypeParameters.As(Of TypeSymbol).Concat(indexedTypeParameters))
Debug.Assert(candidateTypeMap.PairsIncludingParent.Length = arity)
Dim desiredTypeMap = TypeSubstitution.Create(
desiredTypeParameters(0).ContainingSymbol,
desiredTypeParameters,
indexedTypeParameters)
Debug.Assert(desiredTypeMap.PairsIncludingParent.Length = arity)
For i = 0 To arity - 1
If Not MethodSignatureComparer.HaveSameConstraints(candidateMethodDefinition.TypeParameters(i), candidateTypeMap, desiredTypeParameters(i), desiredTypeMap) Then
Return False
End If
Next
Return True
End Function
Private Structure DisplayClassInstanceAndFields
Friend ReadOnly Instance As DisplayClassInstance
Friend ReadOnly Fields As ConsList(Of FieldSymbol)
Friend Sub New(instance As DisplayClassInstance)
MyClass.New(instance, ConsList(Of FieldSymbol).Empty)
Debug.Assert(instance.Type.IsClosureOrStateMachineType() OrElse
GeneratedNames.GetKind(instance.Type.Name) = GeneratedNameKind.AnonymousType)
End Sub
Private Sub New(instance As DisplayClassInstance, fields As ConsList(Of FieldSymbol))
Me.Instance = instance
Me.Fields = fields
End Sub
Friend ReadOnly Property Type As NamedTypeSymbol
Get
Return If(Me.Fields.Any(), DirectCast(Me.Fields.Head.Type, NamedTypeSymbol), Me.Instance.Type)
End Get
End Property
Friend ReadOnly Property Depth As Integer
Get
Return Me.Fields.Count()
End Get
End Property
Friend Function FromField(field As FieldSymbol) As DisplayClassInstanceAndFields
Debug.Assert(field.Type.IsClosureOrStateMachineType() OrElse
GeneratedNames.GetKind(field.Type.Name) = GeneratedNameKind.AnonymousType)
Return New DisplayClassInstanceAndFields(Me.Instance, Me.Fields.Prepend(field))
End Function
Friend Function ToVariable(name As String, kind As DisplayClassVariableKind, field As FieldSymbol) As DisplayClassVariable
Return New DisplayClassVariable(name, kind, Me.Instance, Me.Fields.Prepend(field))
End Function
End Structure
End Class
End Namespace
|
furesoft/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationContext.vb
|
Visual Basic
|
apache-2.0
| 75,432
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Roslyn.Test.Utilities
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Reflection.Metadata
Imports System.Reflection.Metadata.Ecma335
Imports System.Runtime.InteropServices
Imports System.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class AttributeTests_WellKnownAttributes
Inherits BasicTestBase
#Region "InteropAttributes Miscellaneous Tests"
<Fact>
Public Sub TestInteropAttributes01()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<Assembly: ComCompatibleVersion(1, 2, 3, 4)>
<ComImport(), Guid("ABCDEF5D-2448-447A-B786-64682CBEF123")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
<TypeLibImportClass(GetType(Object)), TypeLibType(TypeLibTypeFlags.FAggregatable)>
<BestFitMapping(False, ThrowOnUnmappableChar:=True)>
Public Interface IFoo
<AllowReversePInvokeCalls()>
Sub DoSomething()
<ComRegisterFunction()>
Sub Register(o As Object)
<ComUnregisterFunction()>
Sub UnRegister()
<TypeLibFunc(TypeLibFuncFlags.FDefaultBind)>
Sub LibFunc()
End Interface
]]>
</file>
</compilation>
Dim attributeValidator =
Function(isFromSource As Boolean) _
Sub(m As ModuleSymbol)
Dim assembly = m.ContainingAssembly
Dim compilation = m.DeclaringCompilation
Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace)
Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System")
Dim runtimeNS = DirectCast(sysNS.GetMember("Runtime"), NamespaceSymbol)
Dim interopNS = DirectCast(runtimeNS.GetMember("InteropServices"), NamespaceSymbol)
Dim comCompatibleSym As NamedTypeSymbol = interopNS.GetTypeMembers("ComCompatibleVersionAttribute").First()
' Assembly
Dim attrs = assembly.GetAttributes(comCompatibleSym)
Assert.Equal(1, attrs.Count)
Dim attrSym = attrs.First()
Assert.Equal("ComCompatibleVersionAttribute", attrSym.AttributeClass.Name)
Assert.Equal(4, attrSym.CommonConstructorArguments.Length)
Assert.Equal(0, attrSym.CommonNamedArguments.Length)
Assert.Equal(3, attrSym.CommonConstructorArguments(2).Value)
' get expected attr symbol
Dim guidSym = DirectCast(interopNS.GetTypeMember("GuidAttribute"), NamedTypeSymbol)
Dim ciSym = DirectCast(interopNS.GetTypeMember("ComImportAttribute"), NamedTypeSymbol)
Dim iTypeSym = DirectCast(interopNS.GetTypeMember("InterfaceTypeAttribute"), NamedTypeSymbol)
Dim itCtor = DirectCast(iTypeSym.Constructors.First(), MethodSymbol)
Dim tLibSym = DirectCast(interopNS.GetTypeMember("TypeLibImportClassAttribute"), NamedTypeSymbol)
Dim tLTypeSym = DirectCast(interopNS.GetTypeMember("TypeLibTypeAttribute"), NamedTypeSymbol)
Dim bfmSym = DirectCast(interopNS.GetTypeMember("BestFitMappingAttribute"), NamedTypeSymbol)
' IFoo
Dim ifoo = DirectCast(m.GlobalNamespace.GetTypeMember("IFoo"), NamedTypeSymbol)
Assert.True(ifoo.IsComImport)
' ComImportAttribute is a pseudo-custom attribute, which is not emitted.
If Not isFromSource Then
Assert.Equal(5, ifoo.GetAttributes().Length)
Else
Assert.Equal(6, ifoo.GetAttributes().Length)
' get attr by NamedTypeSymbol
attrSym = ifoo.GetAttribute(ciSym)
Assert.Equal("ComImportAttribute", attrSym.AttributeClass.Name)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
Assert.Equal(0, attrSym.CommonNamedArguments.Length)
End If
attrSym = ifoo.GetAttribute(guidSym)
Assert.Equal("String", attrSym.CommonConstructorArguments(0).Type.ToDisplayString)
Assert.Equal("ABCDEF5D-2448-447A-B786-64682CBEF123", attrSym.CommonConstructorArguments(0).Value)
' get attr by ctor
attrSym = ifoo.GetAttribute(itCtor)
Assert.Equal("System.Runtime.InteropServices.ComInterfaceType", attrSym.CommonConstructorArguments(0).Type.ToDisplayString())
Assert.Equal(ComInterfaceType.InterfaceIsIUnknown, CType(attrSym.CommonConstructorArguments(0).Value, ComInterfaceType))
attrSym = ifoo.GetAttribute(tLibSym)
Assert.Equal("Object", CType(attrSym.CommonConstructorArguments(0).Value, Symbol).ToDisplayString())
attrSym = ifoo.GetAttribute(tLTypeSym)
Assert.Equal(TypeLibTypeFlags.FAggregatable, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibTypeFlags))
attrSym = ifoo.GetAttribute(bfmSym)
Assert.Equal(False, attrSym.CommonConstructorArguments(0).Value)
Assert.Equal(1, attrSym.CommonNamedArguments.Length)
Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString)
Assert.Equal("ThrowOnUnmappableChar", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value)
' =============================
Dim mem = DirectCast(ifoo.GetMembers("DoSomething").First(), MethodSymbol)
Assert.Equal(1, mem.GetAttributes().Length)
attrSym = mem.GetAttributes().First()
Assert.Equal("AllowReversePInvokeCallsAttribute", attrSym.AttributeClass.Name)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
mem = DirectCast(ifoo.GetMembers("Register").First(), MethodSymbol)
attrSym = mem.GetAttributes().First()
Assert.Equal("ComRegisterFunctionAttribute", attrSym.AttributeClass.Name)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
mem = DirectCast(ifoo.GetMembers("UnRegister").First(), MethodSymbol)
Assert.Equal(1, mem.GetAttributes().Length)
mem = DirectCast(ifoo.GetMembers("LibFunc").First(), MethodSymbol)
attrSym = mem.GetAttributes().First()
Assert.Equal(1, attrSym.CommonConstructorArguments.Length)
Assert.Equal(TypeLibFuncFlags.FDefaultBind, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibFuncFlags)) ' 32
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False))
End Sub
<Fact>
Public Sub TestInteropAttributes02()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(1, 2)>
<Assembly: Guid("1234C65D-1234-447A-B786-64682CBEF136")>
<ComVisibleAttribute(False)>
<UnmanagedFunctionPointerAttribute(CallingConvention.StdCall, BestFitMapping:=True, CharSet:=CharSet.Ansi, SetLastError:=True, ThrowOnUnmappableChar:=True)>
Public Delegate Sub DFoo(p1 As Char, p2 As SByte)
<ComDefaultInterface(GetType(Object)), ProgId("ProgId")>
Public Class CFoo
<DispIdAttribute(123)> <LCIDConversion(1), ComConversionLoss()>
Sub Method(p1 As SByte, p2 As String)
End Sub
End Class
<ComVisible(true), TypeIdentifier("1234C65D-1234-447A-B786-64682CBEF136", "EFoo, InteropAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")>
Public Enum EFoo
One
<TypeLibVar(TypeLibVarFlags.FDisplayBind)>
Two
<Obsolete("message", false)>
Three
End Enum
]]>
</file>
</compilation>
Dim attributeValidator = Sub(m As ModuleSymbol)
Dim assembly = m.ContainingAssembly
Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), m.DeclaringSyntaxReferences)
Dim compilation = m.DeclaringCompilation
Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace)
Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System")
' get expected attr symbol
Dim runtimeNS = DirectCast(sysNS.GetMember("Runtime"), NamespaceSymbol)
Dim interopNS = DirectCast(runtimeNS.GetMember("InteropServices"), NamespaceSymbol)
Dim comvSym = DirectCast(interopNS.GetTypeMember("ComVisibleAttribute"), NamedTypeSymbol)
Dim ufPtrSym = DirectCast(interopNS.GetTypeMember("UnmanagedFunctionPointerAttribute"), NamedTypeSymbol)
Dim comdSym = DirectCast(interopNS.GetTypeMember("ComDefaultInterfaceAttribute"), NamedTypeSymbol)
Dim pgidSym = DirectCast(interopNS.GetTypeMember("ProgIdAttribute"), NamedTypeSymbol)
Dim tidSym = DirectCast(interopNS.GetTypeMember("TypeIdentifierAttribute"), NamedTypeSymbol)
Dim dispSym = DirectCast(interopNS.GetTypeMember("DispIdAttribute"), NamedTypeSymbol)
Dim lcidSym = DirectCast(interopNS.GetTypeMember("LCIDConversionAttribute"), NamedTypeSymbol)
Dim comcSym = DirectCast(interopNS.GetTypeMember("ComConversionLossAttribute"), NamedTypeSymbol)
Dim moduleGlobalNS = m.GlobalNamespace
' delegate DFoo
Dim type1 = DirectCast(moduleGlobalNS.GetTypeMember("DFoo"), NamedTypeSymbol)
Assert.Equal(2, type1.GetAttributes().Length)
Dim attrSym = type1.GetAttribute(comvSym)
Assert.Equal(False, attrSym.CommonConstructorArguments(0).Value)
attrSym = type1.GetAttribute(ufPtrSym)
Assert.Equal(1, attrSym.CommonConstructorArguments.Length)
Assert.Equal(CallingConvention.StdCall, CType(attrSym.CommonConstructorArguments(0).Value, CallingConvention)) ' 3
Assert.Equal(4, attrSym.CommonNamedArguments.Length)
Assert.Equal("BestFitMapping", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value)
Assert.Equal("CharSet", attrSym.CommonNamedArguments(1).Key)
Assert.Equal(CharSet.Ansi, CType(attrSym.CommonNamedArguments(1).Value.Value, CharSet))
Assert.Equal("SetLastError", attrSym.CommonNamedArguments(2).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(2).Value.Value)
Assert.Equal("ThrowOnUnmappableChar", attrSym.CommonNamedArguments(3).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(3).Value.Value)
' class CFoo
Dim type2 = DirectCast(moduleGlobalNS.GetTypeMember("CFoo"), NamedTypeSymbol)
Assert.Equal(2, type2.GetAttributes().Length)
attrSym = type2.GetAttribute(comdSym)
Assert.Equal("Object", CType(attrSym.CommonConstructorArguments(0).Value, Symbol).ToDisplayString())
attrSym = type2.GetAttribute(pgidSym)
Assert.Equal("String", attrSym.CommonConstructorArguments(0).Type.ToDisplayString)
Assert.Equal("ProgId", attrSym.CommonConstructorArguments(0).Value)
Dim method = DirectCast(type2.GetMembers("Method").First(), MethodSymbol)
attrSym = method.GetAttribute(dispSym)
Assert.Equal(123, attrSym.CommonConstructorArguments(0).Value)
attrSym = method.GetAttribute(lcidSym)
Assert.Equal(1, attrSym.CommonConstructorArguments(0).Value)
attrSym = method.GetAttribute(comcSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
'' enum EFoo
If compilation IsNot Nothing Then
' Because this is a nopia local type it is only visible from the source assembly.
Dim type3 = DirectCast(globalNS.GetTypeMember("EFoo"), NamedTypeSymbol)
Assert.Equal(2, type3.GetAttributes().Length)
attrSym = type3.GetAttribute(comvSym)
Assert.Equal(True, attrSym.CommonConstructorArguments(0).Value)
attrSym = type3.GetAttribute(tidSym)
Assert.Equal(2, attrSym.CommonConstructorArguments.Length)
Assert.Equal("EFoo, InteropAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", attrSym.CommonConstructorArguments(1).Value)
Dim field = DirectCast(type3.GetMembers("one").First(), FieldSymbol)
Assert.Equal(0, field.GetAttributes().Length)
field = DirectCast(type3.GetMembers("two").First(), FieldSymbol)
Assert.Equal(1, field.GetAttributes().Length)
attrSym = field.GetAttributes.First
Assert.Equal("TypeLibVarAttribute", attrSym.AttributeClass.Name)
Assert.Equal(TypeLibVarFlags.FDisplayBind, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibVarFlags))
field = DirectCast(type3.GetMembers("three").First(), FieldSymbol)
attrSym = field.GetAttributes().First()
Assert.Equal("ObsoleteAttribute", attrSym.AttributeClass.Name)
Assert.Equal(2, attrSym.CommonConstructorArguments.Length)
Assert.Equal("message", attrSym.CommonConstructorArguments(0).Value)
Assert.Equal(False, attrSym.CommonConstructorArguments(1).Value)
End If
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator)
End Sub
<WorkItem(540573, "DevDiv")>
<Fact()>
Public Sub TestPseudoAttributes01()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
<ComImport()>
Public Interface IBar
Function Method1(<OptionalAttribute(), DefaultParameterValue(99UL)> ByRef v As ULong) As ULong
Function Method2(<InAttribute(), Out(), DefaultParameterValue("Ref")> ByRef v As String) As String
Function Method3(<InAttribute(), OptionalAttribute(), DefaultParameterValue(" "c)> v1 As Char,
<Out()> <OptionalAttribute()> <DefaultParameterValue(0.0F)> v2 As Single,
<InAttribute()> <OptionalAttribute()> <DefaultParameterValue(Nothing)> v3 As String)
<PreserveSig()>
Sub Method4(
<DateTimeConstant(123456)> p1 As DateTime,
<DecimalConstant(0, 0, 100, 100, 100)> p2 As Decimal,
<OptionalAttribute(), IDispatchConstant()> ByRef p3 As Object)
End Interface
<Serializable(), StructLayout(LayoutKind.Explicit, Size:=16, Pack:=8, CharSet:=System.Runtime.InteropServices.CharSet.Unicode)>
Public Class CBar
<NonSerialized(), MarshalAs(UnmanagedType.I8), FieldOffset(0)>
Public field As Long
End Class
]]>
</file>
</compilation>
Dim attributeValidator = Sub(m As ModuleSymbol)
Dim assembly = m.ContainingSymbol
Dim sourceAssembly = TryCast(assembly, SourceAssemblySymbol)
Dim sysNS As NamespaceSymbol = Nothing
If sourceAssembly IsNot Nothing Then
sysNS = DirectCast(sourceAssembly.DeclaringCompilation.GlobalNamespace.GetMember("System"), NamespaceSymbol)
Else
Dim peAssembly = DirectCast(assembly, PEAssemblySymbol)
sysNS = DirectCast(peAssembly.CorLibrary.GlobalNamespace.GetMember("System"), NamespaceSymbol)
End If
' get expected attr symbol
Dim runtimeNS = sysNS.GetNamespace("Runtime")
Dim interopNS = runtimeNS.GetNamespace("InteropServices")
Dim compsrvNS = runtimeNS.GetNamespace("CompilerServices")
Dim serSym = sysNS.GetTypeMember("SerializableAttribute")
Dim nosSym = sysNS.GetTypeMember("NonSerializedAttribute")
Dim ciptSym = interopNS.GetTypeMember("ComImportAttribute")
Dim laySym = interopNS.GetTypeMember("StructLayoutAttribute")
Dim sigSym = interopNS.GetTypeMember("PreserveSigAttribute")
Dim offSym = interopNS.GetTypeMember("FieldOffsetAttribute")
Dim mshSym = interopNS.GetTypeMember("MarshalAsAttribute")
Dim optSym = interopNS.GetTypeMember("OptionalAttribute")
Dim inSym = interopNS.GetTypeMember("InAttribute")
Dim outSym = interopNS.GetTypeMember("OutAttribute")
' non pseudo
Dim dtcSym = compsrvNS.GetTypeMember("DateTimeConstantAttribute")
Dim dmcSym = compsrvNS.GetTypeMember("DecimalConstantAttribute")
Dim iscSym = compsrvNS.GetTypeMember("IDispatchConstantAttribute")
Dim globalNS = m.GlobalNamespace
' Interface IBar
Dim type1 = globalNS.GetTypeMember("IBar")
Dim attrSym = type1.GetAttribute(ciptSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
Dim method As MethodSymbol
Dim parm As ParameterSymbol
If sourceAssembly IsNot Nothing Then
' Default attribute is in system.dll not mscorlib. Only do this check for source attributes.
Dim defvSym = interopNS.GetTypeMember("DefaultParameterValueAttribute")
method = type1.GetMember(Of MethodSymbol)("Method1")
parm = method.Parameters(0)
attrSym = parm.GetAttribute(defvSym)
attrSym.VerifyValue(0, TypedConstantKind.Primitive, 99UL)
attrSym = parm.GetAttribute(optSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
method = type1.GetMember(Of MethodSymbol)("Method2")
parm = method.Parameters(0)
Assert.Equal(3, parm.GetAttributes().Length)
attrSym = parm.GetAttribute(defvSym)
attrSym.VerifyValue(0, TypedConstantKind.Primitive, "Ref")
attrSym = parm.GetAttribute(inSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
attrSym = parm.GetAttribute(outSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
method = type1.GetMember(Of MethodSymbol)("Method3")
parm = method.Parameters(1) ' v2
Assert.Equal(3, parm.GetAttributes().Length)
attrSym = parm.GetAttribute(defvSym)
attrSym.VerifyValue(0, TypedConstantKind.Primitive, 0.0F)
attrSym = parm.GetAttribute(optSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
attrSym = parm.GetAttribute(outSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
End If
method = type1.GetMember(Of MethodSymbol)("Method4")
attrSym = method.GetAttributes().First()
Assert.Equal("PreserveSigAttribute", attrSym.AttributeClass.Name)
parm = method.Parameters(0)
attrSym = parm.GetAttributes().First()
Assert.Equal("DateTimeConstantAttribute", attrSym.AttributeClass.Name)
attrSym.VerifyValue(0, TypedConstantKind.Primitive, 123456)
parm = method.Parameters(1)
attrSym = parm.GetAttributes().First()
Assert.Equal("DecimalConstantAttribute", attrSym.AttributeClass.Name)
Assert.Equal(5, attrSym.CommonConstructorArguments.Length)
attrSym.VerifyValue(2, TypedConstantKind.Primitive, 100)
parm = method.Parameters(2)
attrSym = parm.GetAttribute(iscSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
' class CBar
Dim type2 = DirectCast(globalNS.GetTypeMember("CBar"), NamedTypeSymbol)
Assert.Equal(2, type2.GetAttributes().Length)
attrSym = type2.GetAttribute(serSym)
Assert.Equal("SerializableAttribute", attrSym.AttributeClass.Name)
attrSym = type2.GetAttribute(laySym)
attrSym.VerifyValue(0, TypedConstantKind.Enum, CInt(LayoutKind.Explicit))
Assert.Equal(3, attrSym.CommonNamedArguments.Length)
attrSym.VerifyValue(0, "Size", TypedConstantKind.Primitive, 16)
attrSym.VerifyValue(1, "Pack", TypedConstantKind.Primitive, 8)
attrSym.VerifyValue(2, "CharSet", TypedConstantKind.Enum, CInt(CharSet.Unicode))
Dim field = DirectCast(type2.GetMembers("field").First(), FieldSymbol)
Assert.Equal(3, field.GetAttributes().Length)
attrSym = field.GetAttribute(nosSym)
Assert.Equal(0, attrSym.CommonConstructorArguments.Length)
attrSym = field.GetAttribute(mshSym)
attrSym.VerifyValue(0, TypedConstantKind.Enum, CInt(UnmanagedType.I8))
attrSym = field.GetAttribute(offSym)
attrSym.VerifyValue(0, TypedConstantKind.Primitive, 0)
End Sub
' Verify attributes from source .
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator)
End Sub
<WorkItem(531121, "DevDiv")>
<Fact()>
Public Sub TestDecimalConstantAttribute()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Reflection
Module Form1
Public Sub Main()
For Each field In GetType(C).GetFields()
PrintAttribute(field)
Next
End Sub
Private Sub PrintAttribute(field As FieldInfo)
Dim attr = field.GetCustomAttributesData()(0)
Console.WriteLine("{0}, {1}, {2}, {3}, {4}",
attr.ConstructorArguments(0),
attr.ConstructorArguments(1),
attr.ConstructorArguments(2),
attr.ConstructorArguments(3),
attr.ConstructorArguments(4))
End Sub
End Module
Public Class C
Public Const _Min As Decimal = Decimal.MinValue
Public Const _Max As Decimal = Decimal.MaxValue
Public Const _One As Decimal = Decimal.One
Public Const _MinusOne As Decimal = Decimal.MinusOne
Public Const _Zero As Decimal = Decimal.Zero
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=<![CDATA[
(Byte)0, (Byte)128, (UInt32)4294967295, (UInt32)4294967295, (UInt32)4294967295
(Byte)0, (Byte)0, (UInt32)4294967295, (UInt32)4294967295, (UInt32)4294967295
(Byte)0, (Byte)0, (UInt32)0, (UInt32)0, (UInt32)1
(Byte)0, (Byte)128, (UInt32)0, (UInt32)0, (UInt32)1
(Byte)0, (Byte)0, (UInt32)0, (UInt32)0, (UInt32)0
]]>)
End Sub
#End Region
#Region "DllImportAttribute, MethodImplAttribute, PreserveSigAttribute"
''' 6879: Pseudo DllImport looks very different in metadata Metadata: pinvokeimpl(...) +
''' PreserveSig
<WorkItem(540573, "DevDiv")>
<Fact>
Public Sub TestPseudoDllImport()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
''' PreserveSigAttribute: automatically insert by compiler
Public Class DllImportTest
'Metadata - .method public static pinvokeimpl("unmanaged.dll" lasterr fastcall)
' void DllImportSub() cil managed preservesig
<DllImport("unmanaged.dll", CallingConvention:=CallingConvention.FastCall, SetLastError:=True)>
Public Shared Sub DllImportSub()
End Sub
' Metadata .method public static pinvokeimpl("user32.dll" unicode winapi)
' int32 MessageBox(native int hwnd, string t, string caption, uint32 t2) cil managed preservesig
'
' MSDN has table for 'default' ExactSpelling value
' C#|C++: always 'false'
' VB: true if CharSet is ANSI|UniCode; otherwise false
<DllImport("user32.dll", CharSet:=CharSet.Unicode, ExactSpelling:=False, EntryPoint:="MessageBox")> _
Shared Function MessageBox(ByVal hwnd As IntPtr, ByVal t As String, ByVal caption As String, ByVal t2 As UInt32) As Integer
End Function
End Class
]]>
</file>
</compilation>
Dim attributeValidator =
Sub(m As ModuleSymbol)
Dim assembly = m.ContainingAssembly
Dim compilation = m.DeclaringCompilation
Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace)
Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System")
' get expected attr symbol
Dim runtimeNS = sysNS.GetNamespace("Runtime")
Dim interopNS = runtimeNS.GetNamespace("InteropServices")
Dim compsrvNS = runtimeNS.GetNamespace("CompilerServices")
Dim type1 = m.GlobalNamespace.GetTypeMember("DllImportTest")
Dim method As MethodSymbol
method = type1.GetMember(Of MethodSymbol)("DllImportSub")
Dim attrSym = method.GetAttributes().First()
Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name)
Assert.Equal("unmanaged.dll", attrSym.CommonConstructorArguments(0).Value)
Assert.Equal("CallingConvention", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind)
Assert.Equal(CallingConvention.FastCall, CType(attrSym.CommonNamedArguments(0).Value.Value, CallingConvention))
Assert.Equal("SetLastError", attrSym.CommonNamedArguments(1).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(1).Value.Value)
method = DirectCast(type1.GetMembers("MessageBox").First(), MethodSymbol)
attrSym = method.GetAttributes().First()
Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name)
Assert.Equal("user32.dll", attrSym.CommonConstructorArguments(0).Value)
Assert.Equal("CharSet", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind)
Assert.Equal(CharSet.Unicode, CType(attrSym.CommonNamedArguments(0).Value.Value, CharSet))
Assert.Equal("ExactSpelling", attrSym.CommonNamedArguments(1).Key)
Assert.Equal(TypedConstantKind.Primitive, attrSym.CommonNamedArguments(1).Value.Kind)
Assert.Equal(False, attrSym.CommonNamedArguments(1).Value.Value)
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator)
End Sub
<Fact>
Public Sub DllImport_AttributeRedefinition()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Namespace System.Runtime.InteropServices
<DllImport>
Public Class DllImportAttribute
End Class
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_AttributeMustInheritSysAttr, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"))
End Sub
<Fact>
Public Sub DllImport_InvalidArgs1()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic.Strings
Class C
<DllImport(Nothing)>
Public Shared Sub F1()
End Sub
<DllImport("")>
Public Shared Sub F2()
End Sub
<DllImport("foo", EntryPoint:=Nothing)>
Public Shared Sub F3()
End Sub
<DllImport("foo", EntryPoint:="")>
Public Shared Sub F4()
End Sub
<DllImport(Nothing, EntryPoint:=Nothing)>
Public Shared Sub F5()
End Sub
<DllImport(ChrW(0))>
Public Shared Sub Empty1()
End Sub
<DllImport(ChrW(0) & "b")>
Public Shared Sub Empty2()
End Sub
<DllImport("b" & ChrW(0))>
Public Shared Sub Empty3()
End Sub
<DllImport("x" & ChrW(0) & "y")>
Public Shared Sub Empty4()
End Sub
<DllImport("x", EntryPoint:="x" & ChrW(0) & "y")>
Public Shared Sub Empty5()
End Sub
<DllImport(ChrW(&H800))>
Public Shared Sub LeadingSurrogate()
End Sub
<DllImport(ChrW(&HDC00))>
Public Shared Sub TrailingSurrogate()
End Sub
<DllImport(ChrW(&HDC00) & ChrW(&HD800))>
Public Shared Sub ReversedSurrogates1()
End Sub
<DllImport("x", EntryPoint:=ChrW(&HDC00) & ChrW(&HD800))>
Public Shared Sub ReversedSurrogates2()
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadAttribute1, "Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, """""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=""""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(0)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(0) & ""b""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, """b"" & ChrW(0)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, """x"" & ChrW(0) & ""y""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=""x"" & ChrW(0) & ""y""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(&HDC00) & ChrW(&HD800)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=ChrW(&HDC00) & ChrW(&HD800)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"))
End Sub
<Fact>
Public Sub DllImport_SpecialCharactersInName()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic.Strings
Class Program
<DllImport(ChrW(&HFFFF))>
Shared Sub InvalidCharacter()
End Sub
<DllImport(ChrW(&HD800) & ChrW(&HDC00))>
Shared Sub SurrogatePairMin()
End Sub
<DllImport(ChrW(&HDBFF) & ChrW(&HDFFF))>
Shared Sub SurrogatePairMax()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(3, reader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(3, reader.GetTableRowCount(TableIndex.ImplMap))
For Each method In reader.GetImportedMethods()
Dim import = method.GetImport()
Dim moduleName As String = reader.GetString(reader.GetModuleReference(import.Module).Name)
Dim methodName As String = reader.GetString(method.Name)
Select Case methodName
Case "InvalidCharacter"
Assert.Equal(ChrW(&HFFFF), moduleName)
Case "SurrogatePairMin"
Assert.Equal(ChrW(&HD800) & ChrW(&HDC00), moduleName)
Case "SurrogatePairMax"
Assert.Equal(ChrW(&HDBFF) & ChrW(&HDFFF), moduleName)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(methodName)
End Select
Next
End Sub)
End Sub
<Fact>
Public Sub DllImport_TypeCharacterInName()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Module Module1
<DllImport("user32.dll", CharSet:=CharSet.Unicode)>
Function MessageBox%(hwnd As IntPtr, t As String, caption As String, t2 As UInt32)
End Function
End Module
]]>
</file>
</compilation>
Dim attributeValidator =
Sub(m As ModuleSymbol)
Dim type1 = m.GlobalNamespace.GetTypeMember("Module1")
Dim method = DirectCast(type1.GetMembers("MessageBox").First(), MethodSymbol)
Dim attrSym = method.GetAttributes().First()
Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name)
Assert.Equal("user32.dll", attrSym.CommonConstructorArguments(0).Value)
Assert.Equal("CharSet", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind)
Assert.Equal(CharSet.Unicode, CType(attrSym.CommonNamedArguments(0).Value.Value, CharSet))
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator)
End Sub
<Fact()>
<WorkItem(544176, "DevDiv")>
Public Sub TestPseudoAttributes_DllImport_AllTrue()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<DllImport("mscorlib", EntryPoint:="bar", CallingConvention:=CallingConvention.Cdecl, CharSet:=CharSet.Unicode, ExactSpelling:=True, PreserveSig:=True, SetLastError:=True, BestFitMapping:=True, ThrowOnUnmappableChar:=True)>
Public Shared Sub M()
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly, TestEmitters) =
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
' ModuleRef:
Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name
Assert.Equal("mscorlib", reader.GetString(moduleRefName))
' FileRef:
' Although the Metadata spec says there should be a File entry for each ModuleRef entry
' Dev10 compiler doesn't add it and peverify doesn't complain.
Assert.Equal(0, reader.GetTableRowCount(TableIndex.File))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap))
' ImplMap:
Dim import = reader.GetImportedMethods().Single().GetImport()
Assert.Equal("bar", reader.GetString(import.Name))
Assert.Equal(1, reader.GetRowNumber(import.Module))
Assert.Equal(MethodImportAttributes.ExactSpelling Or
MethodImportAttributes.CharSetUnicode Or
MethodImportAttributes.SetLastError Or
MethodImportAttributes.CallingConventionCDecl Or
MethodImportAttributes.BestFitMappingEnable Or
MethodImportAttributes.ThrowOnUnmappableCharEnable, import.Attributes)
' MethodDef:
Dim methodDefs As MethodDefinitionHandle() = reader.MethodDefinitions.AsEnumerable().ToArray()
Assert.Equal(2, methodDefs.Length) ' ctor, M
Assert.Equal(MethodImplAttributes.PreserveSig, reader.GetMethodDefinition(methodDefs(1)).ImplAttributes)
End Sub
Dim symValidator As Action(Of ModuleSymbol) =
Sub(peModule)
Dim c = peModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim m = c.GetMember(Of MethodSymbol)("M")
Dim info = m.GetDllImportData()
Assert.Equal("mscorlib", info.ModuleName)
Assert.Equal("bar", info.EntryPointName)
Assert.Equal(CharSet.Unicode, info.CharacterSet)
Assert.True(info.ExactSpelling)
Assert.True(info.SetLastError)
Assert.Equal(True, info.BestFitMapping)
Assert.Equal(True, info.ThrowOnUnmappableCharacter)
Assert.Equal(
Cci.PInvokeAttributes.NoMangle Or
Cci.PInvokeAttributes.CharSetUnicode Or
Cci.PInvokeAttributes.SupportsLastError Or
Cci.PInvokeAttributes.CallConvCdecl Or
Cci.PInvokeAttributes.BestFitEnabled Or
Cci.PInvokeAttributes.ThrowOnUnmappableCharEnabled, DirectCast(info, Cci.IPlatformInvokeInformation).Flags)
End Sub
CompileAndVerify(source, validator:=validator, symbolValidator:=symValidator)
End Sub
<Fact>
<WorkItem(544601, "DevDiv")>
Public Sub GetDllImportData_UnspecifiedProperties()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DllImport("mscorlib")>
Shared Sub M()
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) =
Function(isFromSource As Boolean) _
Sub([module] As ModuleSymbol)
Dim c = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim m = c.GetMember(Of MethodSymbol)("M")
Dim info = m.GetDllImportData()
Assert.Equal("mscorlib", info.ModuleName)
Assert.Equal(If(isFromSource, Nothing, "M"), info.EntryPointName)
Assert.Equal(CharSet.None, info.CharacterSet)
Assert.Equal(CallingConvention.Winapi, info.CallingConvention)
Assert.False(info.ExactSpelling)
Assert.False(info.SetLastError)
Assert.Equal(Nothing, info.BestFitMapping)
Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter)
End Sub
CompileAndVerify(source, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
<WorkItem(544601, "DevDiv")>
Public Sub GetDllImportData_Declare()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
Declare Unicode Sub M1 Lib "foo"()
Declare Unicode Sub M2 Lib "foo" Alias "bar"()
End Class
]]>
</file>
</compilation>
Dim validator =
Function(isFromSource As Boolean) _
Sub([module] As ModuleSymbol)
Dim c = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim info = c.GetMember(Of MethodSymbol)("M1").GetDllImportData()
Assert.Equal("foo", info.ModuleName)
Assert.Equal(If(isFromSource, Nothing, "M1"), info.EntryPointName)
Assert.Equal(CharSet.Unicode, info.CharacterSet)
Assert.Equal(CallingConvention.Winapi, info.CallingConvention)
Assert.True(info.ExactSpelling)
Assert.True(info.SetLastError)
Assert.Equal(Nothing, info.BestFitMapping)
Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter)
info = c.GetMember(Of MethodSymbol)("M2").GetDllImportData()
Assert.Equal("foo", info.ModuleName)
Assert.Equal("bar", info.EntryPointName)
Assert.Equal(CharSet.Unicode, info.CharacterSet)
Assert.Equal(CallingConvention.Winapi, info.CallingConvention)
Assert.True(info.ExactSpelling)
Assert.True(info.SetLastError)
Assert.Equal(Nothing, info.BestFitMapping)
Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter)
End Sub
CompileAndVerify(source, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
Public Sub TestPseudoAttributes_DllImport_Operators()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<DllImport("foo")>
Public Shared Operator +(a As C, b As C) As Integer
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap))
Dim method = reader.GetImportedMethods().Single()
Dim import = method.GetImport()
Dim moduleName As String = reader.GetString(reader.GetModuleReference(import.Module).Name)
Dim entryPointName As String = reader.GetString(method.Name)
Assert.Equal("op_Addition", entryPointName)
Assert.Equal("foo", moduleName)
End Sub)
End Sub
<Fact>
Public Sub TestPseudoAttributes_DllImport_Conversions()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<DllImport("foo")>
Public Shared Narrowing Operator CType(a As C) As Integer
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
Assert.Equal(1, peFileReader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(1, peFileReader.GetTableRowCount(TableIndex.ImplMap))
Dim method = peFileReader.GetImportedMethods().Single()
Dim moduleName As String = peFileReader.GetString(peFileReader.GetModuleReference(method.GetImport().Module).Name)
Dim entryPointName As String = peFileReader.GetString(method.Name)
Assert.Equal("op_Explicit", entryPointName)
Assert.Equal("foo", moduleName)
End Sub)
End Sub
<Fact>
Public Sub DllImport_Partials()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<DllImport("module name")>
Shared Partial Private Sub foo()
End Sub
Shared Private Sub foo()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap))
Dim method = reader.GetImportedMethods().Single()
Dim moduleName As String = reader.GetString(reader.GetModuleReference(method.GetImport().Module).Name)
Dim entryPointName As String = reader.GetString(method.Name)
Assert.Equal("module name", moduleName)
Assert.Equal("foo", entryPointName)
End Sub)
End Sub
<Fact>
Public Sub DllImport_Partials_Errors()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.InteropServices
Public Class C
<DllImport("module name")>
Partial Private Sub foo()
End Sub
Private Sub foo()
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DllImportOnInstanceMethod, "DllImport"))
End Sub
<Fact>
Public Sub DllImport_Partials_NonEmptyBody()
Dim source =
<compilation>
<file><![CDATA[
Module Module1
<System.Runtime.InteropServices.DllImport("a")>
Private Sub f1()
End Sub
Partial Private Sub f1()
End Sub
<System.Runtime.InteropServices.DllImport("a")>
Partial Private Sub f2()
End Sub
Private Sub f2()
System.Console.WriteLine()
End Sub
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DllImportOnNonEmptySubOrFunction, "System.Runtime.InteropServices.DllImport"))
End Sub
<Fact>
Public Sub TestPseudoAttributes_DllImport_NotAllowed()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Public Class C
Public Shared Property F As Integer
<DllImport("a")>
Get
Return 1
End Get
<DllImport(Nothing)>
Set(value As Integer)
End Set
End Property
Custom Event x As Action(Of Integer)
<DllImport("foo")>
AddHandler(value As Action(Of Integer))
End AddHandler
<DllImport("foo")>
RemoveHandler(value As Action(Of Integer))
End RemoveHandler
<DllImport("foo")>
RaiseEvent(obj As Integer)
End RaiseEvent
End Event
<DllImport("foo")>
Sub InstanceMethod
End Sub
<DllImport("foo")>
Shared Sub NonEmptyBody
System.Console.WriteLine()
End Sub
<DllImport("foo")>
Shared Sub GenericMethod(Of T)()
End Sub
End Class
Interface I
<DllImport("foo")>
Sub InterfaceMethod()
End Interface
Interface I(Of T)
<DllImport("foo")>
Sub InterfaceMethod()
End Interface
Class C(Of T)
Interface Foo
Class D
<DllImport("foo")>
Shared Sub MethodOnGenericType()
End Sub
End Class
End Interface
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DllImportNotLegalOnGetOrSet, "DllImport"),
Diagnostic(ERRID.ERR_DllImportNotLegalOnGetOrSet, "DllImport"),
Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"),
Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"),
Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnInstanceMethod, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnNonEmptySubOrFunction, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnGenericSubOrFunction, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnGenericSubOrFunction, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnInterfaceMethod, "DllImport"),
Diagnostic(ERRID.ERR_DllImportOnInterfaceMethod, "DllImport"))
End Sub
<Fact>
Public Sub TestPseudoAttributes_DllImport_Flags()
Dim cases =
{
New With {.n = 0, .attr = MakeDllImport(), .expected = MethodImportAttributes.CallingConventionWinApi},
New With {.n = 1, .attr = MakeDllImport(cc:=CallingConvention.Cdecl), .expected = MethodImportAttributes.CallingConventionCDecl},
New With {.n = 2, .attr = MakeDllImport(cc:=CallingConvention.FastCall), .expected = MethodImportAttributes.CallingConventionFastCall},
New With {.n = 3, .attr = MakeDllImport(cc:=CallingConvention.StdCall), .expected = MethodImportAttributes.CallingConventionStdCall},
New With {.n = 4, .attr = MakeDllImport(cc:=CallingConvention.ThisCall), .expected = MethodImportAttributes.CallingConventionThisCall},
New With {.n = 5, .attr = MakeDllImport(cc:=CallingConvention.Winapi), .expected = MethodImportAttributes.CallingConventionWinApi},
_
New With {.n = 6, .attr = MakeDllImport(), .expected = MethodImportAttributes.CallingConventionWinApi},
New With {.n = 7, .attr = MakeDllImport(charSet:=CharSet.None), .expected = MethodImportAttributes.CallingConventionWinApi},
New With {.n = 8, .attr = MakeDllImport(charSet:=CharSet.Ansi), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAnsi},
New With {.n = 9, .attr = MakeDllImport(charSet:=CharSet.Unicode), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetUnicode},
New With {.n = 10, .attr = MakeDllImport(charSet:=CharSet.Auto), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAuto},
_
New With {.n = 11, .attr = MakeDllImport(exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling},
New With {.n = 12, .attr = MakeDllImport(exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi},
_
New With {.n = 13, .attr = MakeDllImport(charSet:=CharSet.Ansi, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi},
New With {.n = 14, .attr = MakeDllImport(charSet:=CharSet.Ansi, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAnsi},
New With {.n = 15, .attr = MakeDllImport(charSet:=CharSet.Unicode, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetUnicode},
New With {.n = 16, .attr = MakeDllImport(charSet:=CharSet.Unicode, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetUnicode},
New With {.n = 17, .attr = MakeDllImport(charSet:=CharSet.Auto, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAuto},
New With {.n = 18, .attr = MakeDllImport(charSet:=CharSet.Auto, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAuto},
_
New With {.n = 19, .attr = MakeDllImport(preserveSig:=True), .expected = MethodImportAttributes.CallingConventionWinApi},
New With {.n = 20, .attr = MakeDllImport(preserveSig:=False), .expected = MethodImportAttributes.CallingConventionWinApi},
_
New With {.n = 21, .attr = MakeDllImport(setLastError:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError},
New With {.n = 22, .attr = MakeDllImport(setLastError:=False), .expected = MethodImportAttributes.CallingConventionWinApi},
_
New With {.n = 23, .attr = MakeDllImport(bestFitMapping:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.BestFitMappingEnable},
New With {.n = 24, .attr = MakeDllImport(bestFitMapping:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.BestFitMappingDisable},
_
New With {.n = 25, .attr = MakeDllImport(throwOnUnmappableChar:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ThrowOnUnmappableCharEnable},
New With {.n = 26, .attr = MakeDllImport(throwOnUnmappableChar:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ThrowOnUnmappableCharDisable},
_
New With {.n = 27, .attr = "<DllImport(""bar"", CharSet:=CType(15, CharSet), SetLastError:=True)>", .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError},
New With {.n = 28, .attr = "<DllImport(""bar"", CallingConvention:=CType(15, CallingConvention), SetLastError:=True)>", .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError}
}
' NOTE: case #28 - when an invalid calling convention is specified Dev10 compiler emits invalid metadata (calling convention 0).
' We emit calling convention WinAPI.
Dim sb As StringBuilder = New StringBuilder(
<text>
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
</text>.Value)
For Each testCase In cases
sb.Append(testCase.attr)
sb.AppendLine()
sb.AppendLine("Shared Sub M" & testCase.n & "()")
sb.AppendLine("End Sub")
Next
sb.AppendLine("End Class")
Dim code = <compilation><file name="attr.vb"><%= sb.ToString() %></file></compilation>
CompileAndVerify(code, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(cases.Length, reader.GetTableRowCount(TableIndex.ImplMap))
Dim j = 0
For Each method In reader.GetImportedMethods()
Assert.Equal(cases(j).expected, method.GetImport().Attributes)
j = j + 1
Next
End Sub)
End Sub
Private Function MakeDllImport(Optional cc As CallingConvention? = Nothing, Optional charSet As CharSet? = Nothing, Optional exactSpelling As Boolean? = Nothing, Optional preserveSig As Boolean? = Nothing, Optional setLastError As Boolean? = Nothing, Optional bestFitMapping As Boolean? = Nothing, Optional throwOnUnmappableChar As Boolean? = Nothing) As String
Dim sb As StringBuilder = New StringBuilder("<DllImport(""bar""")
If cc IsNot Nothing Then
sb.Append(", CallingConvention := CallingConvention.")
sb.Append(cc.Value.ToString())
End If
If charSet IsNot Nothing Then
sb.Append(", CharSet := CharSet.")
sb.Append(charSet.Value.ToString())
End If
If exactSpelling IsNot Nothing Then
sb.Append(", ExactSpelling := ")
sb.Append(If(exactSpelling.Value, "True", "False"))
End If
If preserveSig IsNot Nothing Then
sb.Append(", PreserveSig := ")
sb.Append(If(preserveSig.Value, "True", "False"))
End If
If setLastError IsNot Nothing Then
sb.Append(", SetLastError := ")
sb.Append(If(setLastError.Value, "True", "False"))
End If
If bestFitMapping IsNot Nothing Then
sb.Append(", BestFitMapping := ")
sb.Append(If(bestFitMapping.Value, "True", "False"))
End If
If throwOnUnmappableChar IsNot Nothing Then
sb.Append(", ThrowOnUnmappableChar := ")
sb.Append(If(throwOnUnmappableChar.Value, "True", "False"))
End If
sb.Append(")>")
Return sb.ToString()
End Function
<Fact>
Public Sub TestMethodImplAttribute_VerifiableMD()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
MustInherit Class C
<MethodImpl(MethodImplOptions.ForwardRef)>
Public Shared Sub ForwardRef()
System.Console.WriteLine(0)
End Sub
<MethodImpl(MethodImplOptions.NoInlining)>
Public Shared Sub NoInlining()
System.Console.WriteLine(1)
End Sub
<MethodImpl(MethodImplOptions.NoOptimization)>
Public Shared Sub NoOptimization()
System.Console.WriteLine(2)
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Public Shared Sub Synchronized()
System.Console.WriteLine(3)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)> ' ok, body ignored
Public Shared Sub InternalCallStatic()
System.Console.WriteLine(3)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)> ' ok, body ignored
Public Sub InternalCallInstance()
System.Console.WriteLine(3)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)>
Public MustOverride Sub InternalCallAbstract()
End Class
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly, TestEmitters) =
Sub(assembly, options)
Dim isRefEmit = options = TestEmitters.RefEmit
Dim peReader = assembly.GetMetadataReader()
For Each methodDef In peReader.MethodDefinitions
Dim row = peReader.GetMethodDefinition(methodDef)
Dim actualFlags = row.ImplAttributes
Dim expectedFlags As MethodImplAttributes
Select Case peReader.GetString(row.Name)
Case "NoInlining"
expectedFlags = MethodImplAttributes.NoInlining
Case "NoOptimization"
expectedFlags = MethodImplAttributes.NoOptimization
Case "Synchronized"
expectedFlags = MethodImplAttributes.Synchronized
Case "InternalCallStatic", "InternalCallInstance", "InternalCallAbstract"
' workaround for a bug in ref.emit:
expectedFlags = If(isRefEmit, MethodImplAttributes.Runtime Or MethodImplAttributes.InternalCall, MethodImplAttributes.InternalCall)
Case "ForwardRef"
' workaround for a bug in ref.emit:
expectedFlags = If(isRefEmit, Nothing, MethodImplAttributes.ForwardRef)
Case ".ctor"
expectedFlags = MethodImplAttributes.IL
Case Else
Throw TestExceptionUtilities.UnexpectedValue(peReader.GetString(row.Name))
End Select
Assert.Equal(expectedFlags, actualFlags)
Next
End Sub
CompileAndVerify(source, validator:=validator)
End Sub
<Fact>
Public Sub TestMethodImplAttribute_UnverifiableMD()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<MethodImpl(MethodImplOptions.Unmanaged)> ' peverify: type load failed
Public Shared Sub Unmanaged()
System.Console.WriteLine(1)
End Sub
<MethodImpl(MethodCodeType:=MethodCodeType.Native)> ' peverify: type load failed
Public Shared Sub Native()
System.Console.WriteLine(2)
End Sub
<MethodImpl(MethodCodeType:=MethodCodeType.OPTIL)> ' peverify: type load failed
Public Shared Sub OPTIL()
System.Console.WriteLine(3)
End Sub
<MethodImpl(MethodCodeType:=MethodCodeType.Runtime)> ' peverify: type load failed
Public Shared Sub Runtime()
System.Console.WriteLine(4)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)>
Public Shared Sub InternalCallGeneric1(Of T)() ' peverify: type load failed (InternalCall method can't be generic)
End Sub
End Class
Class C(Of T)
<MethodImpl(MethodImplOptions.InternalCall)>
Public Shared Sub InternalCallGeneric2() ' peverify: type load failed (InternalCall method can't be in a generic type)
End Sub
End Class
]]>
</file>
</compilation>)
Dim image = compilation.EmitToArray()
Dim peReader = ModuleMetadata.CreateFromImage(image).Module.GetMetadataReader()
For Each methodDef In peReader.MethodDefinitions
Dim row = peReader.GetMethodDefinition(methodDef)
Dim actualFlags = row.ImplAttributes
Dim actualHasBody = row.RelativeVirtualAddress <> 0
Dim expectedFlags As MethodImplAttributes
Dim expectedHasBody As Boolean
Select Case peReader.GetString(row.Name)
Case "ForwardRef"
expectedFlags = MethodImplAttributes.ForwardRef
expectedHasBody = True
Case "Unmanaged"
expectedFlags = MethodImplAttributes.Unmanaged
expectedHasBody = True
Case "Native"
expectedFlags = MethodImplAttributes.Native
expectedHasBody = True
Case "Runtime"
expectedFlags = MethodImplAttributes.Runtime
expectedHasBody = False
Case "OPTIL"
expectedFlags = MethodImplAttributes.OPTIL
expectedHasBody = True
Case "InternalCallStatic", "InternalCallGeneric1", "InternalCallGeneric2"
expectedFlags = MethodImplAttributes.InternalCall
expectedHasBody = False
Case ".ctor"
expectedFlags = MethodImplAttributes.IL
expectedHasBody = True
Case Else
Throw TestExceptionUtilities.UnexpectedValue(peReader.GetString(row.Name))
End Select
Assert.Equal(expectedFlags, actualFlags)
Assert.Equal(expectedHasBody, actualHasBody)
Next
End Sub
<Fact>
Public Sub TestPseudoAttributes_DllImport_Declare()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.InteropServices
Public Class C
<DllImport("Baz")>
Declare Ansi Sub Foo Lib "Foo" Alias "bar" ()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DllImportNotLegalOnDeclare, "DllImport"))
End Sub
<Fact>
Public Sub ExternalExtensionMethods()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Module M
<Extension()>
<MethodImpl(MethodImplOptions.InternalCall)>
Sub InternalCall(a As Integer)
End Sub
<Extension()>
<DllImport("foo")>
Sub DllImp(a As Integer)
End Sub
<Extension()>
Declare Sub DeclareSub Lib "bar" (a As Integer)
End Module
Class C
Shared Sub Main()
Dim x = 1
x.DeclareSub()
x.DllImp()
x.InternalCall()
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}).VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestMethodImplAttribute_PreserveSig()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
MustInherit Class C
Sub New
End Sub
<PreserveSig>
MustOverride Public Sub f0()
<MethodImpl(MethodImplOptions.PreserveSig)>
MustOverride Public Sub f1()
<DllImport("foo")>
Public Shared Sub f2()
End Sub
<DllImport("foo", PreserveSig:=True)>
Public Shared Sub f3()
End Sub
<DllImport("foo", PreserveSig:=False)>
Public Shared Sub f4()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=True)>
Public Shared Sub f5()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False)>
Public Shared Sub f6()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), PreserveSig>
MustOverride Public Sub f7()
<DllImport("foo"), PreserveSig>
Public Shared Sub f8()
End Sub
<PreserveSig, DllImport("foo", PreserveSig:=True)>
Public Shared Sub f9()
End Sub
' false
<DllImport("foo", PreserveSig:=False), PreserveSig>
Public Shared Sub f10()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=True), PreserveSig>
Public Shared Sub f11()
End Sub
' false
<DllImport("foo", PreserveSig:=False), PreserveSig, MethodImpl(MethodImplOptions.PreserveSig)>
Public Shared Sub f12()
End Sub
' false
<DllImport("foo", PreserveSig:=False), MethodImpl(MethodImplOptions.PreserveSig), PreserveSig>
Public Shared Sub f13()
End Sub
<PreserveSig, DllImport("foo", PreserveSig:=False), MethodImpl(MethodImplOptions.PreserveSig)>
Public Shared Sub f14()
End Sub
<PreserveSig, MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False)>
Public Shared Sub f15()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), PreserveSig, DllImport("foo", PreserveSig:=False)>
Public Shared Sub f16()
End Sub
<MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False), PreserveSig>
Public Shared Sub f17()
End Sub
' false
Public Shared Sub f18()
End Sub
<MethodImpl(MethodImplOptions.Synchronized), DllImport("foo", PreserveSig:=False), PreserveSig>
Public Shared Sub f19()
End Sub
<MethodImpl(MethodImplOptions.Synchronized), PreserveSig>
Public Shared Sub f20()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim peReader = assembly.GetMetadataReader()
For Each methodDef In peReader.MethodDefinitions
Dim row = peReader.GetMethodDefinition(methodDef)
Dim actualFlags = row.ImplAttributes
Dim expectedFlags As MethodImplAttributes
Dim name = peReader.GetString(row.Name)
Select Case name
Case "f0", "f1", "f2", "f3", "f5", "f6", "f7", "f8", "f9", "f11", "f14", "f15", "f16", "f17"
expectedFlags = MethodImplAttributes.PreserveSig
Case "f4", "f10", "f12", "f13", "f18", ".ctor"
expectedFlags = 0
Case "f19"
expectedFlags = MethodImplAttributes.Synchronized
Case "f20"
expectedFlags = MethodImplAttributes.PreserveSig Or MethodImplAttributes.Synchronized
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Assert.Equal(expectedFlags, actualFlags)
Next
' no custom attributes applied on methods:
For Each ca In peReader.CustomAttributes
Dim parent = peReader.GetCustomAttribute(ca).Parent
Assert.NotEqual(parent.Kind, HandleKind.MethodDefinition)
Next
End Sub)
End Sub
<Fact>
Public Sub MethodImplAttribute_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class Program1
<MethodImpl(CShort(0))>
Sub f0()
End Sub
<MethodImpl(CShort(1))>
Sub f1()
End Sub
<MethodImpl(CShort(2))>
Sub f2()
End Sub
<MethodImpl(CShort(3))>
Sub f3()
End Sub
<MethodImpl(CShort(4))>
Sub f4()
End Sub
<MethodImpl(CShort(5))>
Sub f5()
End Sub
<MethodImpl(CType(2, MethodImplOptions))>
Sub f6()
End Sub
<MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))>
Sub f7()
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(1))>
~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(2))>
~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(3))>
~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(5))>
~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CType(2, MethodImplOptions))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'MethodImplAttribute' is not valid: Incorrect argument value.
<MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
Private Sub DisableJITOptimizationTestHelper(
assembly As PEAssembly,
methods As String(),
implFlags As MethodImplAttributes()
)
Dim m = assembly.Modules(0)
Dim dissableOptDef As TypeDefinitionHandle = Nothing
Dim name As String = Nothing
For Each typeDef In m.GetMetadataReader().TypeDefinitions
name = m.GetTypeDefNameOrThrow(typeDef)
If name.Equals("DisableJITOptimization") Then
dissableOptDef = typeDef
Exit For
End If
Next
Assert.NotEqual(Nothing, dissableOptDef)
Dim map As New Dictionary(Of String, MethodDefinitionHandle)()
For Each methodDef In m.GetMethodsOfTypeOrThrow(dissableOptDef)
map.Add(m.GetMethodDefNameOrThrow(methodDef), methodDef)
Next
For i As Integer = 0 To methods.Length - 1
Dim actualFlags As MethodImplAttributes
m.GetMethodDefPropsOrThrow(map(methods(i)), name, actualFlags, Nothing, Nothing)
Assert.Equal(implFlags(i), actualFlags)
Next
End Sub
<Fact>
Public Sub DisableJITOptimization_01()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports Microsoft.VisualBasic
Public Module DisableJITOptimization
Sub Main()
Err.Raise(0)
End Sub
Sub Main2()
Dim x = Sub() Err.Raise(0)
End Sub
End Module
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly, TestEmitters) =
Sub(assembly, _omitted)
Const implFlags As MethodImplAttributes = MethodImplAttributes.IL Or MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization
DisableJITOptimizationTestHelper(assembly, {"Main", "Main2"}, {implFlags, 0})
End Sub
CompileAndVerify(source, validator:=validator)
End Sub
#End Region
#Region "DefaultCharSetAttribute"
<Fact, WorkItem(544518, "DevDiv")>
Public Sub DllImport_DefaultCharSet1()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Module:DefaultCharSet(CharSet.Ansi)>
MustInherit Class C
<DllImport("foo")>
Shared Sub f1()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, emitters:=TestEmitters.CCI, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap))
Assert.False(FindCustomAttribute(reader, "DefaultCharSetAttribute").IsNil)
Dim import = reader.GetImportedMethods().Single().GetImport()
Assert.Equal(MethodImportAttributes.CharSetAnsi, import.Attributes And MethodImportAttributes.CharSetMask)
End Sub)
End Sub
<Fact>
Public Sub DllImport_DefaultCharSet2()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Module:DefaultCharSet(CharSet.None)>
<StructLayout(LayoutKind.Explicit)>
MustInherit Class C
<DllImport("foo")>
Shared Sub f1()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, emitters:=TestEmitters.CCI, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap))
Assert.False(FindCustomAttribute(reader, "DefaultCharSetAttribute").IsNil)
Dim import = reader.GetImportedMethods().Single().GetImport()
Assert.Equal(MethodImportAttributes.None, import.Attributes And MethodImportAttributes.CharSetMask)
For Each typeDef In reader.TypeDefinitions
Dim def = reader.GetTypeDefinition(typeDef)
Dim name = reader.GetString(def.Name)
Select Case name
Case "C"
Assert.Equal(TypeAttributes.ExplicitLayout Or TypeAttributes.Abstract, def.Attributes)
Case "<Module>"
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
End Sub)
End Sub
<Fact>
Public Sub DllImport_DefaultCharSet_Errors()
Dim source =
<compilation>
<file><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Module:DefaultCharSet(DirectCast(Integer.MaxValue, CharSet))>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<![CDATA[
BC30127: Attribute 'DefaultCharSetAttribute' is not valid: Incorrect argument value.
<Module:DefaultCharSet(DirectCast(Integer.MaxValue, CharSet))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>)
End Sub
<Fact>
Public Sub DefaultCharSet_Types()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
<Module:DefaultCharSet(CharSet.Unicode)>
Class C
Class D
Dim arr As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
Sub foo()
Dim a As Integer = 1
Dim b As Integer = 2
Dim q = New With {.f = 1, .g = 2}
Dim z = New Action(Sub() Console.WriteLine(a + arr(b)))
End Sub
End Class
Event Foo(a As Integer, b As String)
End Class
<SpecialName>
Public Class Special
End Class
<StructLayout(LayoutKind.Sequential, Pack:=4, Size:=10)>
Public Structure SeqLayout
End Structure
Structure S
End Structure
Enum E
A
End Enum
Interface I
End Interface
Delegate Sub D()
<Microsoft.VisualBasic.ComClass("", "", "")>
Public Class CC
Public Sub F()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, emitters:=TestEmitters.CCI, validator:=
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
For Each typeDef In peFileReader.TypeDefinitions
Dim row = peFileReader.GetTypeDefinition(typeDef)
Dim name = peFileReader.GetString(row.Name)
Dim actual = row.Attributes And TypeAttributes.StringFormatMask
If name = "<Module>" OrElse
name.StartsWith("__StaticArrayInitTypeSize=", StringComparison.Ordinal) OrElse
name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal) Then
Assert.Equal(TypeAttributes.AnsiClass, actual)
Else
Assert.Equal(TypeAttributes.UnicodeClass, actual)
End If
Next
End Sub)
End Sub
''' <summary>
''' DefaultCharSet is not applied on embedded types.
''' </summary>
<WorkItem(546644, "DevDiv")>
<Fact>
Public Sub DefaultCharSet_EmbeddedTypes()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
<Module:DefaultCharSet(CharSet.Unicode)>
Friend Class C
Public Sub Foo(x As Integer)
Console.WriteLine(ChrW(x))
End Sub
End Class
]]>
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithReferences(source,
references:={MscorlibRef, SystemRef, SystemCoreRef},
options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True))
CompileAndVerify(c, validator:=
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
For Each typeDef In peFileReader.TypeDefinitions
Dim row = peFileReader.GetTypeDefinition(typeDef)
Dim name = peFileReader.GetString(row.Name)
Dim actual = row.Attributes And TypeAttributes.StringFormatMask
If name = "C" Then
Assert.Equal(TypeAttributes.UnicodeClass, actual)
Else
' embedded types should not be affected
Assert.Equal(TypeAttributes.AnsiClass, actual)
End If
Next
End Sub)
End Sub
#End Region
#Region "Declare Method PInvoke Flags"
<Fact>
Public Sub TestPseudoAttributes_Declare_DefaultFlags()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Declare Sub Bar Lib "Foo" ()
End Class
]]>
</file>
</compilation>
Dim validator As Action(Of PEAssembly, TestEmitters) =
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
' ModuleRef:
Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name
Assert.Equal("Foo", reader.GetString(moduleRefName))
' FileRef:
' Although the Metadata spec says there should be a File entry for each ModuleRef entry
' Dev10 compiler doesn't add it and peverify doesn't complain.
Assert.Equal(0, reader.GetTableRowCount(TableIndex.File))
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef))
' ImplMap:
Dim import = reader.GetImportedMethods().Single().GetImport()
Assert.Equal("Bar", reader.GetString(import.Name))
Assert.Equal(1, reader.GetRowNumber(import.Module))
Assert.Equal(MethodImportAttributes.ExactSpelling Or
MethodImportAttributes.CharSetAnsi Or
MethodImportAttributes.CallingConventionWinApi Or
MethodImportAttributes.SetLastError, import.Attributes)
' MethodDef:
Dim methodDefs As MethodDefinitionHandle() = reader.MethodDefinitions.AsEnumerable().ToArray()
Assert.Equal(2, methodDefs.Length) ' ctor, M
Assert.Equal(MethodImplAttributes.PreserveSig, reader.GetMethodDefinition(methodDefs(1)).ImplAttributes)
End Sub
CompileAndVerify(source, validator:=validator)
End Sub
<Fact>
Public Sub TestPseudoAttributes_Declare_Flags()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Declare Ansi Sub _Ansi Lib "a" ()
Declare Unicode Sub _Unicode Lib "b" ()
Declare Auto Sub _Auto Lib "c" ()
Declare Function _Alias Lib "d" Alias "Baz" () As Integer
End Class
]]>
</file>
</compilation>
Const declareFlags = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError
Dim validator As Action(Of PEAssembly, TestEmitters) =
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
Assert.Equal(4, peFileReader.GetTableRowCount(TableIndex.ModuleRef))
Assert.Equal(4, peFileReader.GetTableRowCount(TableIndex.ImplMap))
For Each method In peFileReader.GetImportedMethods()
Dim import = method.GetImport()
Dim moduleName As String = peFileReader.GetString(peFileReader.GetModuleReference(import.Module).Name
)
Dim entryPointName As String = peFileReader.GetString(method.Name)
Dim importname As String = peFileReader.GetString(import.Name)
Select Case entryPointName
Case "_Ansi"
Assert.Equal("a", moduleName)
Assert.Equal("_Ansi", importname)
Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi, import.Attributes)
Case "_Unicode"
Assert.Equal("b", moduleName)
Assert.Equal("_Unicode", importname)
Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetUnicode, import.Attributes)
Case "_Auto"
Assert.Equal("c", moduleName)
Assert.Equal("_Auto", importname)
Assert.Equal(declareFlags Or MethodImportAttributes.CharSetAuto, import.Attributes)
Case "_Alias"
Assert.Equal("d", moduleName)
Assert.Equal("Baz", importname)
Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi, import.Attributes)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(entryPointName)
End Select
Next
End Sub
CompileAndVerify(source, validator:=validator)
End Sub
<Fact>
Public Sub TestPseudoAttributes_Declare_Modifiers()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Public Class D
Shared Declare Sub F1 Lib "d" ()
Static Declare Sub F2 Lib "d" ()
ReadOnly Declare Sub F3 Lib "d" ()
WriteOnly Declare Sub F4 Lib "d" ()
Overrides Declare Sub F5 Lib "d" ()
Overridable Declare Sub F6 Lib "d" ()
MustOverride Declare Sub F7 Lib "d" ()
NotOverridable Declare Sub F8 Lib "d" ()
Overloads Declare Sub F9 Lib "d" ()
Shadows Declare Sub F10 Lib "d" ()
Dim Declare Sub F11 Lib "d" ()
Const Declare Sub F12 Lib "d" ()
Static Declare Sub F13 Lib "d" ()
Default Declare Sub F14 Lib "d" ()
WithEvents Declare Sub F17 Lib "d" ()
Widening Declare Sub F18 Lib "d" ()
Narrowing Declare Sub F19 Lib "d" ()
Partial Declare Sub F20 Lib "d" ()
MustInherit Declare Sub F21 Lib "d" ()
NotInheritable Declare Sub F22 Lib "d" ()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Shared").WithArguments("Shared"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Static").WithArguments("Static"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "ReadOnly").WithArguments("ReadOnly"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "WriteOnly").WithArguments("WriteOnly"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Overrides").WithArguments("Overrides"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Overridable").WithArguments("Overridable"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "MustOverride").WithArguments("MustOverride"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "NotOverridable").WithArguments("NotOverridable"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Dim").WithArguments("Dim"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Const").WithArguments("Const"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Static").WithArguments("Static"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Default").WithArguments("Default"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "WithEvents").WithArguments("WithEvents"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Widening").WithArguments("Widening"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Narrowing").WithArguments("Narrowing"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "Partial").WithArguments("Partial"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "MustInherit").WithArguments("MustInherit"),
Diagnostic(ERRID.ERR_BadDeclareFlags1, "NotInheritable").WithArguments("NotInheritable")
)
End Sub
<Fact>
Public Sub TestPseudoAttributes_Declare_Missing1()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Public Class D
Declare Sub Lib "d" ()
End Class
]]>
</file>
</compilation>
' TODO (tomat): Dev10 only reports ERR_InvalidUseOfKeyword
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Lib"),
Diagnostic(ERRID.ERR_MissingLibInDeclare, "")
)
End Sub
<Fact>
Public Sub TestPseudoAttributes_Declare_Missing2()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Public Class D
Declare Sub $42 Lib "d" ()
End Class
]]>
</file>
</compilation>
' TODO (tomat): Dev10 only reports ERR_IllegalChar
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_IllegalChar, "$")
)
End Sub
#End Region
#Region "InAttribute, OutAttribute"
<Fact()>
Public Sub InOutAttributes()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.InteropServices
Class C
Public Shared Sub M1(<[In]> ByRef a As Integer, <[In]> b As Integer, <[In]> ParamArray c As Object())
End Sub
Public Shared Sub M2(<Out> ByRef d As Integer, <Out> e As Integer, <Out> ParamArray f As Object())
End Sub
Public Shared Sub M3(<[In], Out> ByRef g As Integer, <[In], Out> h As Integer, <[In], [Out]> ParamArray i As Object())
End Sub
Public Shared Sub M4(<[In]>Optional j As Integer = 1, <[Out]>Optional k As Integer = 2, <[In], [Out]>Optional l As Integer = 3)
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
Assert.Equal(12, reader.GetTableRowCount(TableIndex.Param))
For Each paramDef In reader.GetParameters()
Dim row = reader.GetParameter(paramDef)
Dim name As String = reader.GetString(row.Name)
Dim expectedFlags As ParameterAttributes
Select Case name
Case "a", "b", "c"
expectedFlags = ParameterAttributes.In
Case "d", "e", "f"
expectedFlags = ParameterAttributes.Out
Case "g", "h", "i"
expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out
Case "j"
expectedFlags = ParameterAttributes.In Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional
Case "k"
expectedFlags = ParameterAttributes.Out Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional
Case "l"
expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Assert.Equal(expectedFlags, row.Attributes)
Next
End Sub)
End Sub
<Fact()>
Public Sub InOutAttributes_Properties()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System.Runtime.InteropServices
Class C
Public Property P1(<[In], Out>a As String, <[In]>b As String, <Out>c As String) As String
Get
Return Nothing
End Get
Set(<[In], Out>value As String)
End Set
End Property
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim reader = assembly.GetMetadataReader()
' property parameters are copied for both getter and setter
Assert.Equal(3 + 3 + 1, reader.GetTableRowCount(TableIndex.Param))
For Each paramDef In reader.GetParameters()
Dim row = reader.GetParameter(paramDef)
Dim name As String = reader.GetString(row.Name)
Dim expectedFlags As ParameterAttributes
Select Case name
Case "a", "value"
expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out
Case "b"
expectedFlags = ParameterAttributes.In
Case "c"
expectedFlags = ParameterAttributes.Out
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Assert.Equal(expectedFlags, row.Attributes)
Next
End Sub)
End Sub
#End Region
#Region "ParamArrayAttribute"
<WorkItem(529684, "DevDiv")>
<Fact>
Public Sub TestParamArrayAttributeForParams2()
Dim source =
<compilation>
<file name="TestParamArrayAttributeForParams"><![CDATA[
imports System
Module M1
Public Sub Lang(ParamArray list As Integer())
End Sub
Public Sub Both(<[ParamArray]>ParamArray list As Integer())
End Sub
Public Sub Custom(<[ParamArray]>list As Integer())
End Sub
Public Sub None(list As Integer())
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source)
Dim attributeValidator As Action(Of ModuleSymbol) =
Sub(m As ModuleSymbol)
Dim type = DirectCast(m.GlobalNamespace.GetMember("M1"), NamedTypeSymbol)
Dim lang = DirectCast(type.GetMember("Lang"), MethodSymbol)
Dim both = DirectCast(type.GetMember("Both"), MethodSymbol)
Dim custom = DirectCast(type.GetMember("Custom"), MethodSymbol)
Dim none = DirectCast(type.GetMember("None"), MethodSymbol)
Dim attrsLang = lang.Parameters(0).GetAttributes("System", "ParamArrayAttribute")
Dim attrsBoth = both.Parameters(0).GetAttributes("System", "ParamArrayAttribute")
Dim attrsCustom = custom.Parameters(0).GetAttributes("System", "ParamArrayAttribute")
Dim attrsNone = none.Parameters(0).GetAttributes("System", "ParamArrayAttribute")
If TypeOf type Is PENamedTypeSymbol Then
' An attribute is created when loading from metadata
Assert.Equal(0, attrsLang.Count)
Assert.Equal(0, attrsBoth.Count)
Assert.Equal(0, attrsCustom.Count)
Assert.Equal(0, attrsNone.Count)
Assert.Equal(True, lang.Parameters(0).IsParamArray)
Assert.Equal(True, both.Parameters(0).IsParamArray)
Assert.Equal(True, custom.Parameters(0).IsParamArray)
Assert.Equal(False, none.Parameters(0).IsParamArray)
Else
' No attribute because paramarray is a language construct not a custom attribute
Assert.Equal(0, attrsLang.Count)
Assert.Equal(1, attrsBoth.Count)
Assert.Equal(1, attrsCustom.Count)
Assert.Equal(0, attrsNone.Count)
Assert.Equal(True, lang.Parameters(0).IsParamArray)
Assert.Equal(True, both.Parameters(0).IsParamArray)
Assert.Equal(True, custom.Parameters(0).IsParamArray)
Assert.Equal(False, none.Parameters(0).IsParamArray)
End If
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator)
End Sub
#End Region
#Region "SpecialNameAttribute"
<Fact>
Public Sub SpecialName_AllTargets()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
<SpecialName>
Class Z
<SpecialName>
Sub m()
End Sub
<SpecialName>
Dim f As Integer
<SpecialName>
Property p1 As Integer
<SpecialName>
ReadOnly Property p2 As Integer
Get
Return 1
End Get
End Property
<SpecialName>
Property p3 As Integer
<SpecialName()>
Get
Return 1
End Get
<SpecialName>
Set(value As Integer)
End Set
End Property
<SpecialName>
Event e As Action
End Class
<SpecialName>
Module M
<SpecialName>
Public WithEvents we As New Z
<SpecialName>
Sub WEHandler() Handles we.e
End Sub
End Module
Enum En
<SpecialName>
A = 1
<SpecialName>
B
End Enum
<SpecialName>
Structure S
End Structure
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
For Each ca In peFileReader.CustomAttributes
Dim name = GetAttributeName(peFileReader, ca)
Assert.NotEqual("SpecialNameAttribute", name)
Next
For Each typeDef In peFileReader.TypeDefinitions
Dim row = peFileReader.GetTypeDefinition(typeDef)
Dim name = peFileReader.GetString(row.Name)
Select Case name
Case "S", "Z", "M"
Assert.Equal(TypeAttributes.SpecialName, row.Attributes And TypeAttributes.SpecialName)
Case "<Module>", "En"
Assert.Equal(0, row.Attributes And TypeAttributes.SpecialName)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
For Each methodDef In peFileReader.MethodDefinitions
Dim flags = peFileReader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(MethodAttributes.SpecialName, flags And MethodAttributes.SpecialName)
Next
For Each fieldDef In peFileReader.FieldDefinitions
Dim field = peFileReader.GetFieldDefinition(fieldDef)
Dim name = peFileReader.GetString(field.Name)
Dim flags = field.Attributes
Select Case name
Case "En", "value__", "_we", "f", "A", "B"
Assert.Equal(FieldAttributes.SpecialName, flags And FieldAttributes.SpecialName)
Case "_p1", "eEvent"
Assert.Equal(0, flags And FieldAttributes.SpecialName)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
For Each propertyDef In peFileReader.PropertyDefinitions
Dim prop = peFileReader.GetPropertyDefinition(propertyDef)
Dim name = peFileReader.GetString(prop.Name)
Dim flags = prop.Attributes
Select Case name
Case "p1", "p2", "p3"
Assert.Equal(PropertyAttributes.SpecialName, flags And PropertyAttributes.SpecialName)
Case "we"
Assert.Equal(0, flags And PropertyAttributes.SpecialName)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
For Each eventDef In peFileReader.EventDefinitions
Dim flags = peFileReader.GetEventDefinition(eventDef).Attributes
Assert.Equal(EventAttributes.SpecialName, flags And EventAttributes.SpecialName)
Next
End Sub)
End Sub
#End Region
#Region "SerializableAttribute, NonSerializedAttribute"
<Fact>
Public Sub Serializable_NonSerialized_AllTargets()
Dim source =
<compilation>
<file><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
<Serializable>
Class A
<NonSerialized>
Event e1 As Action
<NonSerialized>
Event e3(a As Integer)
End Class
<Serializable>
Module M
<NonSerialized>
Public WithEvents we As New EventClass
Sub WEHandler() Handles we.e2
End Sub
End Module
<Serializable>
Structure B
<NonSerialized>
Dim x As Integer
End Structure
<Serializable>
Enum E
<NonSerialized>
A = 1
End Enum
<Serializable>
Delegate Sub D()
<Serializable>
Class EventClass
<NonSerialized>
Public Event e2()
Sub RaiseEvents()
RaiseEvent e2()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(assembly, _omitted)
Dim peFileReader = assembly.GetMetadataReader()
For Each ca In peFileReader.CustomAttributes
Dim name = GetAttributeName(peFileReader, ca)
Assert.NotEqual("SerializableAttribute", name)
Assert.NotEqual("NonSerializedAttribute", name)
Next
For Each typeDef In peFileReader.TypeDefinitions
Dim row = peFileReader.GetTypeDefinition(typeDef)
Dim name = peFileReader.GetString(row.Name)
Select Case name
Case "A", "B", "D", "E", "EventClass", "M"
Assert.Equal(TypeAttributes.Serializable, row.Attributes And TypeAttributes.Serializable)
Case "<Module>", "StandardModuleAttribute", "e2EventHandler", "e3EventHandler"
Assert.Equal(0, row.Attributes And TypeAttributes.Serializable)
Case Else
Throw TestExceptionUtilities.UnexpectedValue(name)
End Select
Next
For Each fieldDef In peFileReader.FieldDefinitions
Dim field = peFileReader.GetFieldDefinition(fieldDef)
Dim name = peFileReader.GetString(field.Name)
Dim flags = field.Attributes
Select Case name
Case "e1Event", "x", "A", "e2Event", "_we", "e3Event"
Assert.Equal(FieldAttributes.NotSerialized, flags And FieldAttributes.NotSerialized)
Case "value__"
Assert.Equal(0, flags And FieldAttributes.NotSerialized)
End Select
Next
End Sub)
End Sub
<WorkItem(545199, "DevDiv")>
<Fact>
Public Sub Serializable_NonSerialized_CustomEvents()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
<NonSerialized>
Event e1 As Action
End Interface
MustInherit Class C
<NonSerialized>
Custom Event e2 As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
CompilationUtils.AssertTheseDiagnostics(CreateCompilationWithMscorlib(source),
<expected><![CDATA[
BC30662: Attribute 'NonSerializedAttribute' cannot be applied to 'e1' because the attribute is not valid on this declaration type.
<NonSerialized>
~~~~~~~~~~~~~
BC30662: Attribute 'NonSerializedAttribute' cannot be applied to 'e2' because the attribute is not valid on this declaration type.
<NonSerialized>
~~~~~~~~~~~~~
]]></expected>)
End Sub
#End Region
#Region "AttributeUsageAttribute"
<WorkItem(541733, "DevDiv")>
<Fact()>
Public Sub TestSourceOverrideWellKnownAttribute_01()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(AttributeTargets.Class)>
<AttributeUsage(AttributeTargets.Class)>
Class AttributeUsageAttribute
Inherits Attribute
Public Sub New(x As AttributeTargets)
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source)
' BC30663: Attribute 'AttributeUsageAttribute' cannot be applied multiple times.
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "AttributeUsage(AttributeTargets.Class)").WithArguments("AttributeUsageAttribute"))
End Sub
<WorkItem(541733, "DevDiv")>
<Fact()>
Public Sub TestSourceOverrideWellKnownAttribute_02()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)>
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)>
Class AttributeUsageAttribute
Inherits Attribute
Public Sub New(x As AttributeTargets)
End Sub
Public Property AllowMultiple As Boolean
Get
Return False
End Get
Set
End Set
End Property
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary)
Dim attributeValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol)
Dim ns = DirectCast(m.GlobalNamespace.GetMember("System"), NamespaceSymbol)
Dim attrType = ns.GetTypeMember("AttributeUsageAttribute")
Dim attrs = attrType.GetAttributes(attrType)
Assert.Equal(2, attrs.Count)
' Verify attributes
Dim attrSym = attrs(0)
Assert.Equal(1, attrSym.CommonConstructorArguments.Length)
Assert.Equal(TypedConstantKind.Enum, attrSym.CommonConstructorArguments(0).Kind)
Assert.Equal(AttributeTargets.Class, DirectCast(attrSym.CommonConstructorArguments(0).Value, AttributeTargets))
Assert.Equal(1, attrSym.CommonNamedArguments.Length)
Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString)
Assert.Equal("AllowMultiple", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value)
attrSym = attrs(1)
Assert.Equal(1, attrSym.CommonConstructorArguments.Length)
Assert.Equal(TypedConstantKind.Enum, attrSym.CommonConstructorArguments(0).Kind)
Assert.Equal(AttributeTargets.Class, DirectCast(attrSym.CommonConstructorArguments(0).Value, AttributeTargets))
Assert.Equal(1, attrSym.CommonNamedArguments.Length)
Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString)
Assert.Equal("AllowMultiple", attrSym.CommonNamedArguments(0).Key)
Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value)
' Verify AttributeUsage
Dim attributeUage = attrType.GetAttributeUsageInfo()
Assert.Equal(AttributeTargets.Class, attributeUage.ValidTargets)
Assert.Equal(True, attributeUage.AllowMultiple)
Assert.Equal(True, attributeUage.Inherited)
End Sub
' Verify attributes from source and then load metadata to see attributes are written correctly.
CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator)
End Sub
<Fact()>
Public Sub TestSourceOverrideWellKnownAttribute_03()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)> ' First AttributeUsageAttribute is used for determining AttributeUsage.
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= False)>
Class AttributeUsageAttribute
Inherits Attribute
Public Sub New(x As AttributeTargets)
End Sub
Public Property AllowMultiple As Boolean
Get
Return False
End Get
Set
End Set
End Property
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub TestSourceOverrideWellKnownAttribute_03_DifferentOrder()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= False)> ' First AttributeUsageAttribute is used for determining AttributeUsage.
<AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)>
Class AttributeUsageAttribute
Inherits Attribute
Public Sub New(x As AttributeTargets)
End Sub
Public Property AllowMultiple As Boolean
Get
Return False
End Get
Set
End Set
End Property
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)").WithArguments("AttributeUsageAttribute"))
End Sub
<Fact()>
Public Sub TestAttributeUsageInvalidTargets_01()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(0)> ' No error here
Class X
Inherits Attribute
End Class
<AttributeUsage(-1)> ' No error here
Class Y
Inherits Attribute
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub TestAttributeUsageInvalidTargets_02()
Dim source = <compilation>
<file name="attr.vb"><![CDATA[
Namespace System
<AttributeUsage(0)> ' No error here
Class X
Inherits Attribute
End Class
<AttributeUsage(-1)> ' No error here
Class Y
Inherits Attribute
End Class
<X> ' Error here
<Y> ' No Error here
Class Z
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30662: Attribute 'X' cannot be applied to 'Z' because the attribute is not valid on this declaration type.
<X> ' Error here
~
]]></expected>)
End Sub
#End Region
#Region "Security Attributes"
<Fact>
Public Sub TestHostProtectionAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
<System.Security.Permissions.HostProtection(MayLeakOnAbort := true)>
public structure EventDescriptor
end structure
]]>
</file>
</compilation>
Dim attributeValidator As Action(Of ModuleSymbol) =
Sub([module] As ModuleSymbol)
Dim assembly = [module].ContainingAssembly
Dim sourceAssembly = DirectCast(assembly, SourceAssemblySymbol)
Dim compilation = sourceAssembly.DeclaringCompilation
' Get System.Security.Permissions.HostProtection
Dim emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute")
Dim hostProtectionAttr As NamedTypeSymbol = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(emittedName, True)
Assert.NotNull(hostProtectionAttr)
' Verify type security attributes
Dim type = DirectCast([module].GlobalNamespace.GetMember("EventDescriptor"), Microsoft.Cci.ITypeDefinition)
Debug.Assert(type.HasDeclarativeSecurity)
Dim typeSecurityAttributes As IEnumerable(Of Microsoft.Cci.SecurityAttribute) = type.SecurityAttributes
Assert.Equal(1, typeSecurityAttributes.Count())
' Verify <System.Security.Permissions.HostProtection(MayLeakOnAbort := true)>
Dim securityAttribute = typeSecurityAttributes.First()
Assert.Equal(Cci.SecurityAction.LinkDemand, securityAttribute.Action)
Dim typeAttribute = DirectCast(securityAttribute.Attribute, VisualBasicAttributeData)
Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass)
Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length)
typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, True)
End Sub
CompileAndVerify(source, emitters:=TestEmitters.RefEmitBug, sourceSymbolValidator:=attributeValidator)
End Sub
<Fact()>
Public Sub TestValidSecurityAction()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Security.Permissions
Imports System.Security.Principal
<PrincipalPermission(DirectCast(1, SecurityAction))>
<PrincipalPermission(SecurityAction.Assert)>
<PrincipalPermission(SecurityAction.Demand)>
<PrincipalPermission(SecurityAction.Deny)>
<PrincipalPermission(SecurityAction.PermitOnly)>
Class A
End Class
Module Module1
Sub Main()
End Sub
End Module]]>
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact()>
Public Sub TestValidSecurityActionForTypeOrMethod()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Security.Permissions
Imports System.Security
<MySecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<MySecurityAttribute(SecurityAction.Assert)>
<MySecurityAttribute(SecurityAction.Demand)>
<MySecurityAttribute(SecurityAction.Deny)>
<MySecurityAttribute(SecurityAction.InheritanceDemand)>
<MySecurityAttribute(SecurityAction.LinkDemand)>
<MySecurityAttribute(SecurityAction.PermitOnly)>
<MyCodeAccessSecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<MyCodeAccessSecurityAttribute(SecurityAction.Assert)>
<MyCodeAccessSecurityAttribute(SecurityAction.Demand)>
<MyCodeAccessSecurityAttribute(SecurityAction.Deny)>
<MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)>
<MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)>
<MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)>
class Test
<MySecurityAttribute(directcast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<MySecurityAttribute(SecurityAction.Assert)>
<MySecurityAttribute(SecurityAction.Demand)>
<MySecurityAttribute(SecurityAction.Deny)>
<MySecurityAttribute(SecurityAction.InheritanceDemand)>
<MySecurityAttribute(SecurityAction.LinkDemand)>
<MySecurityAttribute(SecurityAction.PermitOnly)>
<MyCodeAccessSecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<MyCodeAccessSecurityAttribute(SecurityAction.Assert)>
<MyCodeAccessSecurityAttribute(SecurityAction.Demand)>
<MyCodeAccessSecurityAttribute(SecurityAction.Deny)>
<MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)>
<MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)>
<MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)>
public shared sub Main()
End Sub
end class
class MySecurityAttribute
inherits SecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
end class
class MyCodeAccessSecurityAttribute
inherits CodeAccessSecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
public shared sub Main()
end sub
end class
]]>
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact()>
Public Sub TestValidSecurityActionsForAssembly()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
imports System
imports System.Security
imports System.Security.Permissions
<assembly: MySecurityAttribute(SecurityAction.RequestMinimum)>
<assembly: MySecurityAttribute(SecurityAction.RequestOptional)>
<assembly: MySecurityAttribute(SecurityAction.RequestRefuse)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)>
class MySecurityAttribute
inherits SecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
end class
class MyCodeAccessSecurityAttribute
inherits CodeAccessSecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
public shared sub Main()
end sub
end class
]]>
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact()>
Public Sub TestInvalidSecurityActionErrors()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Security.Permissions
Public Class MySecurityAttribute
Inherits SecurityAttribute
Public Sub New(action As SecurityAction)
MyBase.New(action)
End Sub
Public Overrides Function CreatePermission() As System.Security.IPermission
Return Nothing
End Function
End Class
<MySecurityAttribute(DirectCast(0, SecurityAction))>
<MySecurityAttribute(DirectCast(11, SecurityAction))>
<MySecurityAttribute(DirectCast(-1, SecurityAction))>
<FileIOPermission(DirectCast(0, SecurityAction))>
<FileIOPermission(DirectCast(11, SecurityAction))>
<FileIOPermission(DirectCast(-1, SecurityAction))>
<FileIOPermission()>
Class A
<FileIOPermission(SecurityAction.Demand)>
Public Field as Integer
End Class
Module Module1
Sub Main()
End Sub
End Module]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "FileIOPermission").WithArguments("action", "Public Overloads Sub New(action As System.Security.Permissions.SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(0, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(0, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(11, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(11, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(-1, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(-1, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(0, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(0, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(11, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(11, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(-1, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(-1, SecurityAction)"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "FileIOPermission").WithArguments("FileIOPermissionAttribute", "Field"))
End Sub
<Fact()>
Public Sub TestMissingSecurityActionErrors()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
imports System.Security
imports System.Security.Permissions
Public Class MySecurityAttribute
Inherits CodeAccessSecurityAttribute
Public Field As Boolean
Public Property Prop As Boolean
Public Overrides Function CreatePermission() As IPermission
Return Nothing
End Function
Public Sub New()
MyBase.New(SecurityAction.Assert)
End Sub
Public Sub New(x As Integer, a1 As SecurityAction)
MyBase.New(a1)
End Sub
End Class
<MySecurityAttribute()>
<MySecurityAttribute(Field := true)>
<MySecurityAttribute(Field := true, Prop := true)>
<MySecurityAttribute(Prop := true)>
<MySecurityAttribute(Prop := true, Field := true)>
<MySecurityAttribute(0, SecurityAction.Assert)>
public class C
end class
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"),
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"),
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"),
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"),
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"),
Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute")
)
End Sub
<Fact()>
Public Sub TestInvalidSecurityActionsForAssemblyErrors()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
imports System.Security
imports System.Security.Permissions
<assembly: MySecurityAttribute(DirectCast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<assembly: MySecurityAttribute(SecurityAction.Assert)>
<assembly: MySecurityAttribute(SecurityAction.Demand)>
<assembly: MySecurityAttribute(SecurityAction.Deny)>
<assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)>
<assembly: MySecurityAttribute(SecurityAction.LinkDemand)>
<assembly: MySecurityAttribute(SecurityAction.PermitOnly)>
<assembly: MyCodeAccessSecurityAttribute(DirectCast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)>
<assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)>
class MySecurityAttribute
inherits SecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
end class
class MyCodeAccessSecurityAttribute
inherits CodeAccessSecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
public shared sub Main()
end sub
end class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source)
VerifyDiagnostics(compilation,
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "DirectCast(1, SecurityAction)").WithArguments("DirectCast(1, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "DirectCast(1, SecurityAction)").WithArguments("DirectCast(1, SecurityAction)"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"))
End Sub
<Fact()>
Public Sub TestInvalidSecurityActionForTypeOrMethod()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Security.Permissions
Imports System.Security
<MySecurityAttribute(SecurityAction.RequestMinimum)>
<MySecurityAttribute(SecurityAction.RequestOptional)>
<MySecurityAttribute(SecurityAction.RequestRefuse)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)>
class Test
<MySecurityAttribute(SecurityAction.RequestMinimum)>
<MySecurityAttribute(SecurityAction.RequestOptional)>
<MySecurityAttribute(SecurityAction.RequestRefuse)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)>
<MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)>
public shared sub Main()
End Sub
end class
class MySecurityAttribute
inherits SecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
end class
class MyCodeAccessSecurityAttribute
inherits CodeAccessSecurityAttribute
public sub new (a as SecurityAction)
mybase.new(a)
end sub
public overrides function CreatePermission() as IPermission
return nothing
end function
public shared sub Main()
end sub
end class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source)
VerifyDiagnostics(compilation,
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"),
Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"))
End Sub
<WorkItem(546623, "DevDiv")>
<Fact>
Public Sub TestSecurityAttributeInvalidTarget()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Security
Imports System.Security.Permissions
Class Program
<MyPermission(SecurityAction.Demand)> _
Private x As Integer
End Class
<AttributeUsage(AttributeTargets.All)> _
Class MyPermissionAttribute
Inherits CodeAccessSecurityAttribute
Public Sub New(action As SecurityAction)
MyBase.New(action)
End Sub
Public Overrides Function CreatePermission() As IPermission
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source)
VerifyDiagnostics(compilation,
Diagnostic(ERRID.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermissionAttribute"))
End Sub
<WorkItem(544929, "DevDiv")>
<Fact>
Public Sub PrincipalPermissionAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
imports System.Security.Permissions
Class Program
<PrincipalPermission(DirectCast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly.
<PrincipalPermission(SecurityAction.Assert)>
<PrincipalPermission(SecurityAction.Demand)>
<PrincipalPermission(SecurityAction.Deny)>
<PrincipalPermission(SecurityAction.InheritanceDemand)> ' BC31209
<PrincipalPermission(SecurityAction.LinkDemand)> ' BC31209
<PrincipalPermission(SecurityAction.PermitOnly)>
public shared sub Main()
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics(Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."),
Diagnostic(ERRID.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"),
Diagnostic(ERRID.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"))
End Sub
<WorkItem(544956, "DevDiv")>
<Fact>
Public Sub SuppressUnmanagedCodeSecurityAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
imports System
<System.Security.SuppressUnmanagedCodeSecurityAttribute>
Class Program
<System.Security.SuppressUnmanagedCodeSecurityAttribute>
public shared sub Main()
End Sub
End Class
]]>
</file>
</compilation>
CompileAndVerify(source)
End Sub
#End Region
#Region "ComImportAttribute"
<Fact>
Public Sub TestCompImport()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<ComImport()>
Public Interface I
Property PI As Object
Event EI As Action
Sub MI()
End Interface
<ComImport>
Public Class C
Dim WithEvents WEC As New EventClass
Property PC As Object
Property QC As Object
Get
Return Nothing
End Get
Set(value AS Object)
End Set
End Property
Custom Event CEC As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Event EC As Action
Sub MC
End Sub
End Class
<ComImport>
Class EventClass
Public Event XEvent()
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, validator:=
Sub(m, _omitted)
Dim reader = m.GetMetadataReader()
For Each methodDef In reader.MethodDefinitions
Dim row = reader.GetMethodDefinition(methodDef)
Dim name = reader.GetString(row.Name)
Dim actual = row.ImplAttributes
Dim expected As MethodImplAttributes
Select Case name
Case ".ctor"
Continue For
Case "get_WEC",
"get_PC",
"set_PC",
"get_QC",
"set_QC",
"add_CEC",
"remove_CEC",
"raise_CEC",
"MC"
' runtime managed internalcall
expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime
Case "set_WEC"
' runtime managed internalcall synchronized
expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime Or MethodImplAttributes.Synchronized
Case "BeginInvoke",
"EndInvoke",
"Invoke"
' runtime managed
expected = MethodImplAttributes.Runtime
Case "get_PI",
"set_PI",
"add_EI",
"remove_EI",
"MI"
' cil managed
expected = MethodImplAttributes.IL
Case "add_XEvent",
"remove_XEvent",
"add_EC",
"remove_EC"
' Dev11: runtime managed internalcall synchronized
' Roslyn: runtime managed internalcall
expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime
End Select
Assert.Equal(expected, actual)
Next
End Sub)
End Sub
#End Region
#Region "ClassInterfaceAttribute"
<Fact>
Public Sub TestClassInterfaceAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
' Valid cases
<Assembly: ClassInterface(ClassInterfaceType.None)>
<ClassInterface(ClassInterfaceType.AutoDispatch)>
Public Class Class1
End Class
<ClassInterface(ClassInterfaceType.AutoDual)>
Public Class Class2
End Class
<ClassInterface(CShort(0))>
Public Class Class4
End Class
<ClassInterface(CShort(1))>
Public Class Class5
End Class
<ClassInterface(CShort(2))>
Public Class Class6
End Class
' Invalid cases
<ClassInterface(DirectCast(-1, ClassInterfaceType))>
Public Class InvalidClass1
End Class
<ClassInterface(DirectCast(3, ClassInterfaceType))>
Public Class InvalidClass2
End Class
<ClassInterface(CShort(-1))>
Public Class InvalidClass3
End Class
<ClassInterface(CShort(3))>
Public Class InvalidClass4
End Class
<ClassInterface(3)>
Public Class InvalidClass5
End Class
<ClassInterface(ClassInterfaceType.None)>
Public Interface InvalidTarget
End Interface
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30127: Attribute 'ClassInterfaceAttribute' is not valid: Incorrect argument value.
<ClassInterface(DirectCast(-1, ClassInterfaceType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'ClassInterfaceAttribute' is not valid: Incorrect argument value.
<ClassInterface(DirectCast(3, ClassInterfaceType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'ClassInterfaceAttribute' is not valid: Incorrect argument value.
<ClassInterface(CShort(-1))>
~~~~~~~~~~
BC30127: Attribute 'ClassInterfaceAttribute' is not valid: Incorrect argument value.
<ClassInterface(CShort(3))>
~~~~~~~~~
BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
'Public Overloads Sub New(classInterfaceType As ClassInterfaceType)': Argument matching parameter 'classInterfaceType' narrows from 'Integer' to 'ClassInterfaceType'.
'Public Overloads Sub New(classInterfaceType As Short)': Argument matching parameter 'classInterfaceType' narrows from 'Integer' to 'Short'.
<ClassInterface(3)>
~~~~~~~~~~~~~~
BC30662: Attribute 'ClassInterfaceAttribute' cannot be applied to 'InvalidTarget' because the attribute is not valid on this declaration type.
<ClassInterface(ClassInterfaceType.None)>
~~~~~~~~~~~~~~
]]></expected>)
End Sub
#End Region
#Region "InterfaceTypeAttribute, TypeLibTypeAttribute"
<Fact>
Public Sub TestInterfaceTypeAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
' Valid cases
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
Public Interface Interface1
End Interface
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
Public Interface Interface2
End Interface
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface Interface4
End Interface
' ComInterfaceType.InterfaceIsIInspectable seems to be undefined in version of mscorlib used by the test framework.
<InterfaceType(DirectCast(3, ComInterfaceType))>
Public Interface Interface3
End Interface
<InterfaceType(CShort(0))>
Public Interface Interface5
End Interface
<InterfaceType(CShort(1))>
Public Interface Interface6
End Interface
<InterfaceType(CShort(2))>
Public Interface Interface7
End Interface
<InterfaceType(CShort(3))>
Public Interface Interface8
End Interface
' Invalid cases
<InterfaceType(DirectCast(-1, ComInterfaceType))>
Public Interface InvalidInterface1
End Interface
<InterfaceType(DirectCast(4, ComInterfaceType))>
Public Interface InvalidInterface2
End Interface
<InterfaceType(CShort(-1))>
Public Interface InvalidInterface3
End Interface
<InterfaceType(CShort(4))>
Public Interface InvalidInterface4
End Interface
<InterfaceType(4)>
Public Interface InvalidInterface5
End Interface
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
Public Class InvalidTarget
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30127: Attribute 'InterfaceTypeAttribute' is not valid: Incorrect argument value.
<InterfaceType(DirectCast(-1, ComInterfaceType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'InterfaceTypeAttribute' is not valid: Incorrect argument value.
<InterfaceType(DirectCast(4, ComInterfaceType))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30127: Attribute 'InterfaceTypeAttribute' is not valid: Incorrect argument value.
<InterfaceType(CShort(-1))>
~~~~~~~~~~
BC30127: Attribute 'InterfaceTypeAttribute' is not valid: Incorrect argument value.
<InterfaceType(CShort(4))>
~~~~~~~~~
BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
'Public Overloads Sub New(interfaceType As ComInterfaceType)': Argument matching parameter 'interfaceType' narrows from 'Integer' to 'ComInterfaceType'.
'Public Overloads Sub New(interfaceType As Short)': Argument matching parameter 'interfaceType' narrows from 'Integer' to 'Short'.
<InterfaceType(4)>
~~~~~~~~~~~~~
BC30662: Attribute 'InterfaceTypeAttribute' cannot be applied to 'InvalidTarget' because the attribute is not valid on this declaration type.
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
~~~~~~~~~~~~~
]]></expected>)
End Sub
<WorkItem(546664, "DevDiv")>
<Fact()>
Public Sub TestIsExtensibleInterface()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
' InterfaceTypeAttribute
' Extensible interface
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
Public Interface ExtensibleInterface1
End Interface
' Not Extensible interface
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface NotExtensibleInterface1
End Interface
' Extensible interface via inheritance
Public Interface ExtensibleInterface2
Inherits ExtensibleInterface1
End Interface
' TypeLibTypeAttribute
' Extensible interface
<TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))>
Public Interface ExtensibleInterface3
End Interface
' Extensible interface
<TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)>
Public Interface ExtensibleInterface4
End Interface
' Extensible interface
<TypeLibTypeAttribute(0)>
Public Interface ExtensibleInterface5
End Interface
' Extensible interface via inheritance
Public Interface ExtensibleInterface6
Inherits ExtensibleInterface3
End Interface
' Not Extensible interface
<TypeLibTypeAttribute(TypeLibTypeFlags.FNonExtensible)>
Public Interface NotExtensibleInterface2
End Interface
' Not Extensible interface
<TypeLibTypeAttribute(CType(TypeLibTypeFlags.FNonExtensible Or TypeLibTypeFlags.FAppObject, Int16))>
Public Interface NotExtensibleInterface3
End Interface
]]>
</file>
</compilation>, options:=TestOptions.ReleaseDll)
Dim validator =
Sub(m As ModuleSymbol)
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface1").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface2").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface3").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface4").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface5").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface6").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface1").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface2").IsExtensibleInterfaceNoUseSiteDiagnostics())
Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface3").IsExtensibleInterfaceNoUseSiteDiagnostics())
End Sub
CompileAndVerify(compilation, sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<WorkItem(546664, "DevDiv")>
<Fact()>
Public Sub TestIsExtensibleInterface_LateBinding()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
' InterfaceTypeAttribute
' Extensible interface
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
Public Interface ExtensibleInterface1
End Interface
' Not Extensible interface
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface NotExtensibleInterface1
End Interface
' Extensible interface via inheritance
Public Interface ExtensibleInterface2
Inherits ExtensibleInterface1
End Interface
' TypeLibTypeAttribute
' Extensible interface
<TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))>
Public Interface ExtensibleInterface3
End Interface
' Extensible interface
<TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)>
Public Interface ExtensibleInterface4
End Interface
' Extensible interface
<TypeLibTypeAttribute(0)>
Public Interface ExtensibleInterface5
End Interface
' Extensible interface via inheritance
Public Interface ExtensibleInterface6
Inherits ExtensibleInterface3
End Interface
' Not Extensible interface
<TypeLibTypeAttribute(TypeLibTypeFlags.FNonExtensible)>
Public Interface NotExtensibleInterface2
End Interface
' Not Extensible interface
<TypeLibTypeAttribute(CType(TypeLibTypeFlags.FNonExtensible Or TypeLibTypeFlags.FAppObject, Int16))>
Public Interface NotExtensibleInterface3
End Interface
Public Class C
Dim fExtensible1 As ExtensibleInterface1
Dim fExtensible2 As ExtensibleInterface2
Dim fExtensible3 As ExtensibleInterface3
Dim fExtensible4 As ExtensibleInterface4
Dim fExtensible5 As ExtensibleInterface5
Dim fExtensible6 As ExtensibleInterface6
Dim fNotExtensible1 As NotExtensibleInterface1
Dim fNotExtensible2 As NotExtensibleInterface2
Dim fNotExtensible3 As NotExtensibleInterface3
Public Sub Foo()
fExtensible1.LateBound()
fExtensible2.LateBound()
fExtensible3.LateBound()
fExtensible4.LateBound()
fExtensible5.LateBound()
fExtensible6.LateBound()
fNotExtensible1.LateBound()
fNotExtensible2.LateBound()
fNotExtensible3.LateBound()
End Sub
End Class
]]>
</file>
</compilation>, options:=TestOptions.ReleaseDll)
Dim expectedErrors =
<errors><![CDATA[
BC30456: 'LateBound' is not a member of 'NotExtensibleInterface1'.
fNotExtensible1.LateBound()
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'LateBound' is not a member of 'NotExtensibleInterface2'.
fNotExtensible2.LateBound()
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'LateBound' is not a member of 'NotExtensibleInterface3'.
fNotExtensible3.LateBound()
~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<WorkItem(546664, "DevDiv")>
<Fact()>
Public Sub Bug16489_StackOverflow()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
Module Module1
Class XAttribute
Inherits Attribute
Public Sub New(x As Object)
End Sub
End Class
Sub Main()
End Sub
<InterfaceType(CType(3, ComInterfaceType))>
<X(DirectCast(New Object(), II1).GoHome())>
Interface II1
End Interface
Property I1 As II2
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
<X(DirectCast(New Object(), II2).GoHome())>
Interface II2
End Interface
Property I2 As II2
<TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))>
<X(DirectCast(New Object(), II3).GoHome())>
Interface II3
End Interface
Property I3 As II3
<TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)>
<X(DirectCast(New Object(), II4).GoHome())>
Interface II4
End Interface
Property I4 As II4
End Module
]]>
</file>
</compilation>)
Dim expectedErrors =
<errors><![CDATA[
BC30059: Constant expression is required.
<X(DirectCast(New Object(), II1).GoHome())>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<X(DirectCast(New Object(), II2).GoHome())>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<X(DirectCast(New Object(), II3).GoHome())>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<X(DirectCast(New Object(), II4).GoHome())>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
#End Region
#Region "TypeLibVersionAttribute"
<Fact>
Public Sub TestTypeLibVersionAttribute_Valid()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: TypeLibVersionAttribute(0, Integer.MaxValue)>
Class C
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestTypeLibVersionAttribute_Valid2()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: TypeLibVersionAttribute(2147483647, CInt(C.CS * C.CS))>
Public Class C
Public Const CS As Integer = Short.MaxValue
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestTypeLibVersionAttribute_Invalid()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30127: Attribute 'TypeLibVersionAttribute' is not valid: Incorrect argument value.
<Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)>
~~
BC30127: Attribute 'TypeLibVersionAttribute' is not valid: Incorrect argument value.
<Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)>
~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact>
Public Sub TestTypeLibVersionAttribute_Invalid_02()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: TypeLibVersionAttribute("str", 0)>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute.
<Assembly: TypeLibVersionAttribute("str", 0)>
~~~~~
]]></expected>)
End Sub
#End Region
#Region "ComCompatibleVersionAttribute"
<Fact>
Public Sub TestComCompatibleVersionAttribute_Valid()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ComCompatibleVersionAttribute(0, 0, 0, 0)>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertNoErrors(comp)
End Sub
<Fact>
Public Sub TestComCompatibleVersionAttribute_Invalid()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30127: Attribute 'ComCompatibleVersionAttribute' is not valid: Incorrect argument value.
<Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)>
~~
BC30127: Attribute 'ComCompatibleVersionAttribute' is not valid: Incorrect argument value.
<Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)>
~~
BC30127: Attribute 'ComCompatibleVersionAttribute' is not valid: Incorrect argument value.
<Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)>
~~
BC30127: Attribute 'ComCompatibleVersionAttribute' is not valid: Incorrect argument value.
<Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)>
~~
]]></expected>)
End Sub
<Fact>
Public Sub TestComCompatibleVersionAttribute_Invalid_02()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ComCompatibleVersionAttribute("str", 0, 0, 0)>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute.
<Assembly: ComCompatibleVersionAttribute("str", 0, 0, 0)>
~~~~~
]]></expected>)
End Sub
#End Region
#Region "GuidAttribute"
<Fact>
Public Sub TestInvalidGuidAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
<ComImport>
<Guid("69D3E2A0-BB0F-4FE3-9860-ED714C510756")> ' valid (36 chars)
Class A
End Class
<Guid("69D3E2A0-BB0F-4FE3-9860-ED714C51075")> ' incorrect length (35 chars)
Class B
End Class
<Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ' invalid format
Class C
End Class
<Guid("")> ' empty string
Class D
End Class
<Guid(Nothing)> ' Nothing
Class E
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0-BB0F-4FE3-9860-ED714C51075' is not correct.
<Guid("69D3E2A0-BB0F-4FE3-9860-ED714C51075")> ' incorrect length (35 chars)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F--4FE3-9860-ED714C510756' is not correct.
<Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ' invalid format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '' is not correct.
<Guid("")> ' empty string
~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID 'Nothing' is not correct.
<Guid(Nothing)> ' Nothing
~~~~~~~
]]></expected>)
End Sub
<WorkItem(545490, "DevDiv")>
<Fact>
Public Sub TestInvalidGuidAttribute_02()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
' Following are alternate valid Guid formats, but disallowed by the native compiler. Ensure we disallow them.
' 32 digits, no hyphens
<Guid("69D3E2A0BB0F4FE39860ED714C510756")>
Class A
End Class
' 32 digits separated by hyphens, enclosed in braces
<Guid("{69D3E2A0-BB0F-4FE3-9860-ED714C510756}")>
Class B
End Class
' 32 digits separated by hyphens, enclosed in parentheses
<Guid("(69D3E2A0-BB0F-4FE3-9860-ED714C510756)")>
Class C
End Class
' Four hexadecimal values enclosed in braces, where the fourth value is a subset of eight hexadecimal values that is also enclosed in braces
<Guid("{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}")>
Class D
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F4FE39860ED714C510756' is not correct.
<Guid("69D3E2A0BB0F4FE39860ED714C510756")>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '{69D3E2A0-BB0F-4FE3-9860-ED714C510756}' is not correct.
<Guid("{69D3E2A0-BB0F-4FE3-9860-ED714C510756}")>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '(69D3E2A0-BB0F-4FE3-9860-ED714C510756)' is not correct.
<Guid("(69D3E2A0-BB0F-4FE3-9860-ED714C510756)")>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}' is not correct.
<Guid("{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}")>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact>
Public Sub TestInvalidGuidAttribute_Assembly()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.InteropServices
' invalid format
<Assembly: Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")>
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC32500: 'GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F--4FE3-9860-ED714C510756' is not correct.
<Assembly: Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
#End Region
#Region "WindowsRuntimeImportAttribute"
<Fact>
<WorkItem(531295, "DevDiv")>
Public Sub TestWindowsRuntimeImportAttribute()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Namespace System.Runtime.InteropServices.WindowsRuntime
<AttributeUsage(AttributeTargets.[Class] Or AttributeTargets.[Interface] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited := False)>
Friend NotInheritable Class WindowsRuntimeImportAttribute
Inherits Attribute
Public Sub New()
End Sub
End Class
End Namespace
<System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImport>
Class A
Public Shared Sub Main()
End Sub
End Class
]]>
</file>
</compilation>
Dim sourceValidator =
Sub(m As ModuleSymbol)
Dim assembly = m.ContainingSymbol
Dim sysNS = DirectCast(m.DeclaringCompilation.GlobalNamespace.GetMember("System"), NamespaceSymbol)
Dim runtimeNS = sysNS.GetNamespace("Runtime")
Dim interopNS = runtimeNS.GetNamespace("InteropServices")
Dim windowsRuntimeNS = interopNS.GetNamespace("WindowsRuntime")
Dim windowsRuntimeImportAttrType = windowsRuntimeNS.GetTypeMembers("WindowsRuntimeImportAttribute").First()
Dim typeA = m.GlobalNamespace.GetTypeMember("A")
Assert.Equal(1, typeA.GetAttributes(windowsRuntimeImportAttrType).Count)
Assert.True(typeA.IsWindowsRuntimeImport, "Metadata flag not set for IsWindowsRuntimeImport")
End Sub
Dim metadataValidator =
Sub(m As ModuleSymbol)
Dim typeA = m.GlobalNamespace.GetTypeMember("A")
Assert.Equal(0, typeA.GetAttributes().Length)
Assert.True(typeA.IsWindowsRuntimeImport, "Metadata flag not set for IsWindowsRuntimeImport")
End Sub
' Verify that PEVerify will fail despite the fact that compiler produces no errors
' This is consistent with Dev10 behavior
'
' Dev10 PEVerify failure:
' [token 0x02000003] Type load failed.
'
' Dev10 Runtime Exception:
' Unhandled Exception: System.TypeLoadException: Windows Runtime types can only be declared in Windows Runtime assemblies.
Dim validator = CompileAndVerify(source, emitters:=TestEmitters.CCI, sourceSymbolValidator:=sourceValidator, symbolValidator:=metadataValidator, verify:=False)
validator.EmitAndVerify("Type load failed.")
End Sub
#End Region
#Region "STAThreadAttribute, MTAThreadAttribute"
Private Sub VerifySynthesizedSTAThreadAttribute(sourceMethod As SourceMethodSymbol, expected As Boolean)
Dim synthesizedAttributes = sourceMethod.GetSynthesizedAttributes()
If expected Then
Assert.Equal(1, synthesizedAttributes.Length)
Dim attribute = synthesizedAttributes(0)
Dim compilation = sourceMethod.DeclaringCompilation
Dim sysNS = DirectCast(compilation.GlobalNamespace.GetMember("System"), NamespaceSymbol)
Dim attributeType As NamedTypeSymbol = sysNS.GetTypeMember("STAThreadAttribute")
Dim attributeTypeCtor = DirectCast(compilation.GetWellKnownTypeMember(WellKnownMember.System_STAThreadAttribute__ctor), MethodSymbol)
Assert.Equal(attributeType, attribute.AttributeClass)
Assert.Equal(attributeTypeCtor, attribute.AttributeConstructor)
Assert.Equal(0, attribute.ConstructorArguments.Count)
Assert.Equal(0, attribute.NamedArguments.Count)
Else
Assert.Equal(0, synthesizedAttributes.Length)
End If
End Sub
<Fact>
Public Sub TestSynthesizedSTAThread()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub foo()
End Sub
Sub Main()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
compilation.AssertNoErrors()
Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol)
Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol)
Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False)
Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=True)
End Sub
CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator, expectedOutput:="")
End Sub
<Fact>
Public Sub TestNoSynthesizedSTAThread_01()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub foo()
End Sub
Sub Main()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseDll)
compilation.AssertNoErrors()
Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol)
Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol)
Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False)
Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False)
End Sub
CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator)
End Sub
<Fact>
Public Sub TestNoSynthesizedSTAThread_02()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Sub foo()
End Sub
<STAThread()>
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
compilation.AssertNoErrors()
Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol)
Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol)
Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False)
Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False)
End Sub
CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator)
End Sub
<Fact>
Public Sub TestNoSynthesizedSTAThread_03()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Sub foo()
End Sub
<MTAThread()>
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
compilation.AssertNoErrors()
Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol)
Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol)
Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False)
Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol)
VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False)
End Sub
CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator)
End Sub
#End Region
#Region "RequiredAttributeAttribute"
<Fact, WorkItem(81)>
Public Sub DisallowRequiredAttributeInSource()
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Namespace VBClassLibrary
<System.Runtime.CompilerServices.RequiredAttribute(GetType(RS))>
Public Structure RS
Public F1 As Integer
Public Sub New(ByVal p1 As Integer)
F1 = p1
End Sub
End Structure
<System.Runtime.CompilerServices.RequiredAttribute(GetType(RI))>
Public Interface RI
Function F() As Integer
End Interface
Public Class CRI
Implements RI
Public Function F() As Integer Implements RI.F
F = 0
End Function
Public Shared Frs As RS = New RS(0)
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib(source)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC37235: The RequiredAttribute attribute is not permitted on Visual Basic types.
<System.Runtime.CompilerServices.RequiredAttribute(GetType(RS))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37235: The RequiredAttribute attribute is not permitted on Visual Basic types.
<System.Runtime.CompilerServices.RequiredAttribute(GetType(RI))>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(81)>
Public Sub DisallowRequiredAttributeFromMetadata01()
Dim ilSource = <![CDATA[
.class public auto ansi beforefieldinit RequiredAttrClass
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 59 53 79 73 74 65 6D 2E 49 6E 74 33 32 2C // ..YSystem.Int32,
20 6D 73 63 6F 72 6C 69 62 2C 20 56 65 72 73 69 // mscorlib, Versi
6F 6E 3D 34 2E 30 2E 30 2E 30 2C 20 43 75 6C 74 // on=4.0.0.0, Cult
75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 75 62 // ure=neutral, Pub
6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 62 37 37 61 // licKeyToken=b77a
35 63 35 36 31 39 33 34 65 30 38 39 00 00 ) // 5c561934e089..
.field public int32 intVar
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method RequiredAttrClass::.ctor
} // end of class RequiredAttrClass
]]>
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Module M
Sub Main()
Dim r = New RequiredAttrClass()
System.Console.WriteLine(r)
End Sub
End Module
]]>
</file>
</compilation>
Dim ilReference = CompileIL(ilSource.Value)
Dim comp = CreateCompilationWithMscorlibAndReferences(source, references:={MsvbRef, ilReference})
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30649: 'RequiredAttrClass' is an unsupported type.
Dim r = New RequiredAttrClass()
~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(81)>
Public Sub DisallowRequiredAttributeFromMetadata02()
Dim ilSource = <![CDATA[
.class public auto ansi beforefieldinit RequiredAttr.Scenario1
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 59 53 79 73 74 65 6D 2E 49 6E 74 33 32 2C // ..YSystem.Int32,
20 6D 73 63 6F 72 6C 69 62 2C 20 56 65 72 73 69 // mscorlib, Versi
6F 6E 3D 34 2E 30 2E 30 2E 30 2C 20 43 75 6C 74 // on=4.0.0.0, Cult
75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 75 62 // ure=neutral, Pub
6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 62 37 37 61 // licKeyToken=b77a
35 63 35 36 31 39 33 34 65 30 38 39 00 00 ) // 5c561934e089..
.field public int32 intVar
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Scenario1::.ctor
} // end of class RequiredAttr.Scenario1
.class public auto ansi beforefieldinit RequiredAttr.ReqAttrUsage
extends [mscorlib]System.Object
{
.field public class RequiredAttr.Scenario1 sc1_field
.method public hidebysig newslot specialname virtual
instance class RequiredAttr.Scenario1
get_sc1_prop() cil managed
{
// Code size 9 (0x9)
.maxstack 1
.locals (class RequiredAttr.Scenario1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::sc1_field
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ret
} // end of method ReqAttrUsage::get_sc1_prop
.method public hidebysig instance class RequiredAttr.Scenario1
sc1_method() cil managed
{
// Code size 9 (0x9)
.maxstack 1
.locals (class RequiredAttr.Scenario1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::sc1_field
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ret
} // end of method ReqAttrUsage::sc1_method
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method ReqAttrUsage::.ctor
.property instance class RequiredAttr.Scenario1
sc1_prop()
{
.get instance class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::get_sc1_prop()
} // end of property ReqAttrUsage::sc1_prop
} // end of class RequiredAttr.ReqAttrUsage
]]>
Dim source = <compilation>
<file name="a.vb">
<![CDATA[
Imports RequiredAttr
Public Class C
Public Shared Function Main() As Integer
Dim r = New ReqAttrUsage()
r.sc1_field = Nothing
Dim o As Object = r.sc1_prop
r.sc1_method()
Return 1
End Function
End Class
]]>
</file>
</compilation>
Dim ilReference = CompileIL(ilSource.Value)
Dim comp = CreateCompilationWithMscorlib(source, references:={ilReference})
CompilationUtils.AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30656: Field 'sc1_field' is of an unsupported type.
r.sc1_field = Nothing
~~~~~~~~~~~
BC30643: Property 'sc1_prop' is of an unsupported type.
Dim o As Object = r.sc1_prop
~~~~~~~~
BC30657: 'sc1_method' has a return type that is not supported or parameter types that are not supported.
r.sc1_method()
~~~~~~~~~~
]]></expected>)
End Sub
#End Region
<Fact, WorkItem(807, "https://github.com/dotnet/roslyn/issues/807")>
Public Sub TestAttributePropagationForAsyncAndIterators()
Dim source =
<compilation>
<file name="attr.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Class Program
Shared Sub Main()
End Sub
<MyAttribute>
<System.Diagnostics.DebuggerNonUserCodeAttribute>
<System.Diagnostics.DebuggerHiddenAttribute>
<System.Diagnostics.DebuggerStepperBoundaryAttribute>
<System.Diagnostics.DebuggerStepThroughAttribute>
Public Async Function test1() As Task(Of Integer)
Return Await DoNothing()
End Function
Public Async Function test2() As Task(Of Integer)
Return Await DoNothing()
End Function
Private Async Function DoNothing() As Task(Of Integer)
Return 1
End Function
<MyAttribute>
<System.Diagnostics.DebuggerNonUserCodeAttribute>
<System.Diagnostics.DebuggerHiddenAttribute>
<System.Diagnostics.DebuggerStepperBoundaryAttribute>
<System.Diagnostics.DebuggerStepThroughAttribute>
Public Iterator Function Test3() As IEnumerable(Of Integer)
Yield 1
Yield 2
End Function
Public Iterator Function Test4() As IEnumerable(Of Integer)
Yield 1
Yield 2
End Function
End Class
Class MyAttribute
Inherits System.Attribute
End Class
]]>
</file>
</compilation>
Dim attributeValidator As Action(Of ModuleSymbol) =
Sub(m As ModuleSymbol)
Dim program = m.GlobalNamespace.GetTypeMember("Program")
Assert.Equal("", CheckAttributePropagation(DirectCast(program.GetMember(Of MethodSymbol)("test1").
GetAttributes("System.Runtime.CompilerServices", "AsyncStateMachineAttribute").Single().
ConstructorArguments.Single().Value, NamedTypeSymbol).
GetMember(Of MethodSymbol)("MoveNext")))
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", DirectCast(program.GetMember(Of MethodSymbol)("test2").
GetAttributes("System.Runtime.CompilerServices", "AsyncStateMachineAttribute").Single().
ConstructorArguments.Single().Value, NamedTypeSymbol).
GetMember(Of MethodSymbol)("MoveNext").GetAttributes().Single().AttributeClass.ToTestDisplayString())
Assert.Equal("", CheckAttributePropagation(DirectCast(program.GetMember(Of MethodSymbol)("Test3").
GetAttributes("System.Runtime.CompilerServices", "IteratorStateMachineAttribute").Single().
ConstructorArguments.Single().Value, NamedTypeSymbol).
GetMember(Of MethodSymbol)("MoveNext")))
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", DirectCast(program.GetMember(Of MethodSymbol)("Test4").
GetAttributes("System.Runtime.CompilerServices", "IteratorStateMachineAttribute").Single().
ConstructorArguments.Single().Value, NamedTypeSymbol).
GetMember(Of MethodSymbol)("MoveNext").GetAttributes().Single().AttributeClass.ToTestDisplayString())
End Sub
CompileAndVerify(CreateCompilationWithMscorlib45AndVBRuntime(source), symbolValidator:=attributeValidator)
End Sub
Private Shared Function CheckAttributePropagation(moveNext As MethodSymbol) As String
Dim result = ""
If moveNext.GetAttributes("", "MyAttribute").Any() Then
result += "MyAttribute is present" & vbCr
End If
If Not moveNext.GetAttributes("System.Diagnostics", "DebuggerNonUserCodeAttribute").Any() Then
result += "DebuggerNonUserCodeAttribute is missing" & vbCr
End If
If Not moveNext.GetAttributes("System.Diagnostics", "DebuggerHiddenAttribute").Any() Then
result += "DebuggerHiddenAttribute is missing" & vbCr
End If
If Not moveNext.GetAttributes("System.Diagnostics", "DebuggerStepperBoundaryAttribute").Any() Then
result += "DebuggerStepperBoundaryAttribute is missing" & vbCr
End If
If Not moveNext.GetAttributes("System.Diagnostics", "DebuggerStepThroughAttribute").Any() Then
result += "DebuggerStepThroughAttribute is missing" & vbCr
End If
If Not moveNext.GetAttributes("System.Runtime.CompilerServices", "CompilerGeneratedAttribute").Any() Then
result += "CompilerGeneratedAttribute is missing" & vbCr
End If
Return result
End Function
End Class
End Namespace
|
dsplaisted/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.vb
|
Visual Basic
|
apache-2.0
| 202,474
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
'This portion of the binder converts StatementSyntax nodes into BoundStatements
Partial Friend Class Binder
' !!! PLEASE KEEP BindStatement FUNCTION AT THE TOP !!!
''' <summary>
''' The dispatcher method that handles syntax nodes for all stand-alone statements.
''' </summary>
Public Overridable Function BindStatement(node As StatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
Select Case node.Kind
Case SyntaxKind.SimpleAssignmentStatement,
SyntaxKind.AddAssignmentStatement,
SyntaxKind.SubtractAssignmentStatement,
SyntaxKind.MultiplyAssignmentStatement,
SyntaxKind.DivideAssignmentStatement,
SyntaxKind.IntegerDivideAssignmentStatement,
SyntaxKind.ExponentiateAssignmentStatement,
SyntaxKind.LeftShiftAssignmentStatement,
SyntaxKind.RightShiftAssignmentStatement,
SyntaxKind.ConcatenateAssignmentStatement
Return BindAssignmentStatement(DirectCast(node, AssignmentStatementSyntax), diagnostics)
Case SyntaxKind.MidAssignmentStatement
Return BindMidAssignmentStatement(DirectCast(node, AssignmentStatementSyntax), diagnostics)
Case SyntaxKind.AddHandlerStatement,
SyntaxKind.RemoveHandlerStatement
Return BindAddRemoveHandlerStatement(DirectCast(node, AddRemoveHandlerStatementSyntax), diagnostics)
Case SyntaxKind.RaiseEventStatement
Return BindRaiseEventStatement(DirectCast(node, RaiseEventStatementSyntax), diagnostics)
Case SyntaxKind.PrintStatement
Return BindPrintStatement(DirectCast(node, PrintStatementSyntax), diagnostics)
Case SyntaxKind.ExpressionStatement
Return BindExpressionStatement(DirectCast(node, ExpressionStatementSyntax), diagnostics)
Case SyntaxKind.CallStatement
Return BindCallStatement(DirectCast(node, CallStatementSyntax), diagnostics)
Case SyntaxKind.GoToStatement
Return BindGoToStatement(DirectCast(node, GoToStatementSyntax), diagnostics)
Case SyntaxKind.LabelStatement
Return BindLabelStatement(DirectCast(node, LabelStatementSyntax), diagnostics)
Case SyntaxKind.SingleLineIfStatement
Return BindSingleLineIfStatement(DirectCast(node, SingleLineIfStatementSyntax), diagnostics)
Case SyntaxKind.MultiLineIfBlock
Return BindMultiLineIfBlock(DirectCast(node, MultiLineIfBlockSyntax), diagnostics)
Case SyntaxKind.ElseIfStatement
' ElseIf without a preceding If.
Debug.Assert(node.ContainsDiagnostics)
Dim condition = BindBooleanExpression(DirectCast(node, ElseIfStatementSyntax).Condition, diagnostics)
Return New BoundBadStatement(node, ImmutableArray.Create(Of BoundNode)(condition), hasErrors:=True)
Case SyntaxKind.SelectBlock
Return BindSelectBlock(DirectCast(node, SelectBlockSyntax), diagnostics)
Case SyntaxKind.CaseStatement
' Valid Case statement within Select Case statement is handled in BindSelectBlock.
' We should reach here only for invalid Case statements which are not inside any SelectBlock.
' Parser must have already reported error ERRID.ERR_CaseNoSelect or ERRID.ERR_SubRequiresSingleStatement.
Debug.Assert(node.ContainsDiagnostics)
Dim caseStatement = DirectCast(node, CaseStatementSyntax)
Dim statement = BindCaseStatement(caseStatement, selectExpressionOpt:=Nothing, convertCaseElements:=False, diagnostics:=diagnostics)
Return New BoundBadStatement(node, ImmutableArray.Create(Of BoundNode)(statement), hasErrors:=True)
Case SyntaxKind.LocalDeclarationStatement
Return BindLocalDeclaration(DirectCast(node, LocalDeclarationStatementSyntax), diagnostics)
Case SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock,
SyntaxKind.DoLoopUntilBlock
Return BindDoLoop(DirectCast(node, DoLoopBlockSyntax), diagnostics)
Case SyntaxKind.WhileBlock
Return BindWhileBlock(DirectCast(node, WhileBlockSyntax), diagnostics)
Case SyntaxKind.ForBlock
Return BindForToBlock(DirectCast(node, ForOrForEachBlockSyntax), diagnostics)
Case SyntaxKind.ForEachBlock
Return BindForEachBlock(DirectCast(node, ForOrForEachBlockSyntax), diagnostics)
Case SyntaxKind.WithBlock
Return BindWithBlock(DirectCast(node, WithBlockSyntax), diagnostics)
Case SyntaxKind.UsingBlock
Return BindUsingBlock(DirectCast(node, UsingBlockSyntax), diagnostics)
Case SyntaxKind.SyncLockBlock
Return BindSyncLockBlock(DirectCast(node, SyncLockBlockSyntax), diagnostics)
Case SyntaxKind.TryBlock
Return BindTryBlock(DirectCast(node, TryBlockSyntax), diagnostics)
Case SyntaxKind.ExitDoStatement,
SyntaxKind.ExitForStatement,
SyntaxKind.ExitSelectStatement,
SyntaxKind.ExitTryStatement,
SyntaxKind.ExitWhileStatement,
SyntaxKind.ExitFunctionStatement,
SyntaxKind.ExitSubStatement,
SyntaxKind.ExitPropertyStatement
Return BindExitStatement(DirectCast(node, ExitStatementSyntax), diagnostics)
Case SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement, SyntaxKind.ContinueWhileStatement
Return BindContinueStatement(DirectCast(node, ContinueStatementSyntax), diagnostics)
Case SyntaxKind.ReturnStatement
Return BindReturn(DirectCast(node, ReturnStatementSyntax), diagnostics)
Case SyntaxKind.YieldStatement
Return BindYield(DirectCast(node, YieldStatementSyntax), diagnostics)
Case SyntaxKind.ThrowStatement
Return BindThrow(DirectCast(node, ThrowStatementSyntax), diagnostics)
Case SyntaxKind.ErrorStatement
Return BindError(DirectCast(node, ErrorStatementSyntax), diagnostics)
Case SyntaxKind.EmptyStatement
Return New BoundNoOpStatement(node)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.OperatorBlock
Return BindMethodBlock(DirectCast(node, MethodBlockBaseSyntax), diagnostics)
Case SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement
Return BindRedimStatement(DirectCast(node, ReDimStatementSyntax), diagnostics)
Case SyntaxKind.EraseStatement
Return BindEraseStatement(DirectCast(node, EraseStatementSyntax), diagnostics)
Case SyntaxKind.NextStatement,
SyntaxKind.EndIfStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndUsingStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.EndWithStatement,
SyntaxKind.EndSyncLockStatement,
SyntaxKind.EndNamespaceStatement,
SyntaxKind.EndModuleStatement,
SyntaxKind.EndClassStatement,
SyntaxKind.EndStructureStatement,
SyntaxKind.EndInterfaceStatement,
SyntaxKind.EndEnumStatement,
SyntaxKind.EndSubStatement,
SyntaxKind.EndFunctionStatement,
SyntaxKind.EndOperatorStatement,
SyntaxKind.EndPropertyStatement,
SyntaxKind.EndGetStatement,
SyntaxKind.EndSetStatement,
SyntaxKind.EndEventStatement,
SyntaxKind.EndAddHandlerStatement,
SyntaxKind.EndRemoveHandlerStatement,
SyntaxKind.EndRaiseEventStatement,
SyntaxKind.FinallyStatement,
SyntaxKind.IncompleteMember
' This can happen for two reasons:
' 1. if there are more end block statements than block statements in source
' 2. we have nested blocks where the inner one contains a statement that closes a block above the
' nested block (e.g. two nested SyncLocks + end sub in the inner one). Then there will be parser
' generated "End XXX" statements which are only marked as "missing", because the diagnostic will be
' attached to the begin of the block. Both of these missing end statements have a 0 width which causes
' them to be in the same region of a textspan. In that situation the inner end statement may be bound
' separately (outside of the block context) and we need to relax the assertion below to allow missing
' end statements as well (the list of statements was taken from the parser method CreateMissingEnd,
' where only the ones that can appear in a method body have been selected).
'
' We simply need to ignore this, the error is already created by the parser.
Debug.Assert(node.ContainsDiagnostics OrElse
(node.IsMissing AndAlso
(node.Parent.Kind = SyntaxKind.MultiLineSubLambdaExpression OrElse
node.Parent.Kind = SyntaxKind.MultiLineFunctionLambdaExpression OrElse
node.Parent.Kind = SyntaxKind.AddHandlerAccessorBlock OrElse
node.Parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock OrElse
node.Parent.Kind = SyntaxKind.RaiseEventAccessorBlock OrElse
node.Parent.Kind = SyntaxKind.MultiLineIfBlock OrElse
node.Parent.Kind = SyntaxKind.ElseIfBlock OrElse
node.Parent.Kind = SyntaxKind.ElseBlock OrElse
node.Parent.Kind = SyntaxKind.SimpleDoLoopBlock OrElse
node.Parent.Kind = SyntaxKind.DoWhileLoopBlock OrElse
node.Parent.Kind = SyntaxKind.DoUntilLoopBlock OrElse
node.Parent.Kind = SyntaxKind.WhileBlock OrElse
node.Parent.Kind = SyntaxKind.WithBlock OrElse
node.Parent.Kind = SyntaxKind.ForBlock OrElse
node.Parent.Kind = SyntaxKind.ForEachBlock OrElse
node.Parent.Kind = SyntaxKind.SyncLockBlock OrElse
node.Parent.Kind = SyntaxKind.SelectBlock OrElse
node.Parent.Kind = SyntaxKind.TryBlock OrElse
node.Parent.Kind = SyntaxKind.UsingBlock)))
Return New BoundBadStatement(node, ImmutableArray(Of BoundNode).Empty, hasErrors:=True)
Case SyntaxKind.SimpleLoopStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.LoopUntilStatement
' a loop statement is legal as long as it is part of a do loop block
If Not SyntaxFacts.IsDoLoopBlock(node.Parent.Kind) Then
Debug.Assert(node.ContainsDiagnostics)
Dim whileOrUntilClause = DirectCast(node, LoopStatementSyntax).WhileOrUntilClause
Dim childNodes = If(whileOrUntilClause Is Nothing,
ImmutableArray(Of BoundNode).Empty,
ImmutableArray.Create(Of BoundNode)(BindBooleanExpression(whileOrUntilClause.Condition, diagnostics)))
Return New BoundBadStatement(node, childNodes, hasErrors:=True)
End If
Case SyntaxKind.CatchStatement
' a catch statement is legal as long as it is part of a catch block
If Not node.Parent.Kind = SyntaxKind.CatchBlock Then
Debug.Assert(node.ContainsDiagnostics)
Dim whenClause = DirectCast(node, CatchStatementSyntax).WhenClause
Dim childNodes = If(whenClause Is Nothing,
ImmutableArray(Of BoundNode).Empty,
ImmutableArray.Create(Of BoundNode)(BindBooleanExpression(whenClause.Filter, diagnostics)))
Return New BoundBadStatement(node, childNodes, hasErrors:=True)
End If
Case SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ResumeLabelStatement
Return BindResumeStatement(DirectCast(node, ResumeStatementSyntax), diagnostics)
Case SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToLabelStatement, SyntaxKind.OnErrorResumeNextStatement
Return BindOnErrorStatement(node, diagnostics)
Case SyntaxKind.StopStatement
Return BindStopStatement(DirectCast(node, StopOrEndStatementSyntax))
Case SyntaxKind.EndStatement
Return BindEndStatement(DirectCast(node, StopOrEndStatementSyntax), diagnostics)
End Select
' NOTE: Our normal pattern would be to add cases for all of the SyntaxKinds that we know we're
' not handling here and then throwing ExceptionUtilities.UnexpectedValue in the else case, but
' there are just too many statement SyntaxKinds in VB (e.g. declarations, statements corresponding
' to blocks handled above, etc).
Debug.Assert(node.ContainsDiagnostics)
Return New BoundBadStatement(node, ImmutableArray(Of BoundNode).Empty, hasErrors:=True)
End Function
Private Function BindMethodBlock(methodBlock As MethodBlockBaseSyntax, diagnostics As DiagnosticBag) As BoundBlock
Dim statements As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance
Dim locals As ImmutableArray(Of LocalSymbol) = ImmutableArray(Of LocalSymbol).Empty
Dim methodSymbol = DirectCast(ContainingMember, MethodSymbol)
Dim localForFunctionValue As LocalSymbol
If methodSymbol.IsIterator OrElse (methodSymbol.IsAsync AndAlso methodSymbol.ReturnType.Equals(Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task))) Then
' We are actually not using FunctionValue of such method in Return statements and referencing it explicitly is an error.
localForFunctionValue = Nothing
Else
localForFunctionValue = Me.GetLocalForFunctionValue()
End If
If localForFunctionValue IsNot Nothing Then
' Declare local variable for function return
statements.Add(New BoundLocalDeclaration(methodBlock.BlockStatement,
localForFunctionValue,
Nothing))
End If
Dim blockBinder = Me.GetBinder(DirectCast(methodBlock, VisualBasicSyntaxNode))
Dim body = blockBinder.BindBlock(methodBlock, methodBlock.Statements, diagnostics)
' Implicit label to branch to for Exit Sub/Exit Function statements.
Dim exitLabelStatement = New BoundLabelStatement(methodBlock.EndBlockStatement, blockBinder.GetReturnLabel())
If body IsNot Nothing Then
' See if we have to generate OnError handler
Dim containsAwait As Boolean
Dim containsOnError As Boolean ' The block contains an [On Error] statement.
Dim containsResume As Boolean ' The block contains a [Resume [...]] or an [On Error Resume Next] statement.
Dim resumeWithoutLabel As StatementSyntax = Nothing ' The first [Resume], [Resume Next] or [On Error Resume Next] statement, if any.
Dim containsLineNumberLabel As Boolean
Dim containsCatch As Boolean
Dim reportedAnError As Boolean
CheckOnErrorAndAwaitWalker.VisitBlock(blockBinder, body, diagnostics,
containsAwait, containsOnError, containsResume, resumeWithoutLabel,
containsLineNumberLabel, containsCatch,
reportedAnError)
If blockBinder.IsInAsyncContext() AndAlso Not blockBinder.IsInIteratorContext() AndAlso
Not containsAwait AndAlso Not body.HasErrors AndAlso
TypeOf methodBlock.BlockStatement Is MethodStatementSyntax Then
ReportDiagnostic(diagnostics, DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier, ERRID.WRN_AsyncLacksAwaits)
End If
If Not reportedAnError AndAlso
(containsOnError OrElse containsResume OrElse (containsCatch AndAlso containsLineNumberLabel)) Then
' This method uses Unstructured Exception-Handling or needs to track line number
' Note that in constructors this handler does not extend over the call to New at the beginning
' of the constructor.
If methodSymbol.MethodKind = MethodKind.Constructor Then
Dim hasMyBaseConstructorCall As Boolean = False
If InitializerRewriter.HasExplicitMeConstructorCall(body, ContainingMember.ContainingType, hasMyBaseConstructorCall) OrElse hasMyBaseConstructorCall Then
' Move the explicit constructor call out of the block
statements.Add(body.Statements(0))
body = body.Update(body.StatementListSyntax, body.Locals, body.Statements.RemoveAt(0))
End If
End If
' The implicit exitLabelStatement should be the last statement inside BoundUnstructuredExceptionHandlingStatement
' in order to make sure that explicit returns do not bypass a call to Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError.
body = body.Update(body.StatementListSyntax, body.Locals, body.Statements.Add(exitLabelStatement))
statements.Add(New BoundUnstructuredExceptionHandlingStatement(methodBlock,
containsOnError,
containsResume,
resumeWithoutLabel,
containsLineNumberLabel,
body.MakeCompilerGenerated()).MakeCompilerGenerated())
Else
locals = body.Locals
statements.AddRange(body.Statements)
statements.Add(exitLabelStatement)
End If
' Don't allow any further declaration of implicit variables (by speculative binding, say).
DisallowFurtherImplicitVariableDeclaration(diagnostics)
' Add implicitly declared variables, if any.
Dim implicitLocals = Me.ImplicitlyDeclaredVariables
If implicitLocals.Length > 0 Then
If locals.IsEmpty Then
locals = implicitLocals
Else
locals = implicitLocals.Concat(locals)
End If
End If
' Report conflicts between Static variables.
ReportNameConfictsBetweenStaticLocals(blockBinder, diagnostics)
Else
statements.Add(exitLabelStatement)
End If
' Add a Return statement at the end of the function, with a label to branch to for Exit Sub/Exit Function statements.
' The code rewriter turns all returns inside the method body to a jump to the exit label. These returns are the only
' ones that will become real returns in the method body.
' add indirect return sequence
' and maybe an indirect result local (if this is a function)
If localForFunctionValue IsNot Nothing Then
If locals.IsEmpty Then
locals = ImmutableArray.Create(localForFunctionValue)
Else
Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance()
localBuilder.Add(localForFunctionValue)
localBuilder.AddRange(locals)
locals = localBuilder.ToImmutableAndFree()
End If
statements.Add(New BoundReturnStatement(methodBlock.EndBlockStatement, New BoundLocal(methodBlock.EndBlockStatement, localForFunctionValue, isLValue:=False, type:=localForFunctionValue.Type), Nothing, Nothing))
Else
statements.Add(New BoundReturnStatement(methodBlock.EndBlockStatement, Nothing, Nothing, Nothing))
End If
Return New BoundBlock(methodBlock, If(methodBlock IsNot Nothing, methodBlock.Statements, Nothing), locals, statements.ToImmutableAndFree())
End Function
''' <summary>
''' Check presence of [On Error]/[Resume] statements and report diagnostics based on presence of other
''' "incompatible" statements.
''' Report Async/Await diagnostics, which depends on surrounding context.
''' </summary>
Private Class CheckOnErrorAndAwaitWalker
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
Private ReadOnly _binder As Binder
Private ReadOnly _diagnostics As DiagnosticBag
Private _containsOnError As Boolean ' The block contains an [On Error] statement.
Private _containsTry As Boolean ' The block contains a Try block.
Private _containsResume As Boolean ' The block contains a [Resume [...]] or an [On Error Resume Next] statement. And this is a syntax node for the first of them.
Private _resumeWithoutLabel As StatementSyntax ' The first [Resume], [Resume Next] or [On Error Resume Next] statement, if any.
Private _containsLineNumberLabel As Boolean
Private _containsCatch As Boolean
Private _reportedAnError As Boolean
Private _enclosingSyncLockOrUsing As BoundStatement
Private _isInCatchFinallyOrSyncLock As Boolean
Private _containsAwait As Boolean
Private ReadOnly _tryOnErrorResume As New ArrayBuilder(Of BoundStatement)
Private Sub New(binder As Binder, diagnostics As DiagnosticBag)
_diagnostics = diagnostics
_binder = binder
End Sub
Public Shared Shadows Sub VisitBlock(
binder As Binder,
block As BoundBlock,
diagnostics As DiagnosticBag,
<Out> ByRef containsAwait As Boolean,
<Out> ByRef containsOnError As Boolean,
<Out> ByRef containsResume As Boolean,
<Out> ByRef resumeWithoutLabel As StatementSyntax,
<Out> ByRef containsLineNumberLabel As Boolean,
<Out> ByRef containsCatch As Boolean,
<Out> ByRef reportedAnError As Boolean
)
Dim walker As New CheckOnErrorAndAwaitWalker(binder, diagnostics)
Try
walker.Visit(block)
Debug.Assert(walker._enclosingSyncLockOrUsing Is Nothing)
Debug.Assert(Not walker._isInCatchFinallyOrSyncLock)
Catch ex As CancelledByStackGuardException
ex.AddAnError(diagnostics)
reportedAnError = True
End Try
containsAwait = walker._containsAwait
containsOnError = walker._containsOnError
containsResume = walker._containsResume
reportedAnError = walker._reportedAnError
resumeWithoutLabel = walker._resumeWithoutLabel
containsLineNumberLabel = walker._containsLineNumberLabel
containsCatch = walker._containsCatch
If (containsOnError OrElse containsResume) AndAlso walker._containsTry Then
For Each node In walker._tryOnErrorResume
binder.ReportDiagnostic(diagnostics, node.Syntax, ERRID.ERR_TryAndOnErrorDoNotMix)
Next
reportedAnError = True
End If
End Sub
Public Overrides Function Visit(node As BoundNode) As BoundNode
' Do not dive into expressions, unless we are in Async context
If Not _binder.IsInAsyncContext() AndAlso TypeOf node Is BoundExpression Then
Return Nothing
End If
Return MyBase.Visit(node)
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Debug.Assert(Not node.WasCompilerGenerated)
_containsTry = True
_tryOnErrorResume.Add(node)
Visit(node.TryBlock)
Dim save_m_isInCatchFinallyOrSyncLock As Boolean = _isInCatchFinallyOrSyncLock
_isInCatchFinallyOrSyncLock = True
VisitList(node.CatchBlocks)
Visit(node.FinallyBlockOpt)
_isInCatchFinallyOrSyncLock = save_m_isInCatchFinallyOrSyncLock
Return Nothing
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Debug.Assert(Not node.WasCompilerGenerated)
_containsOnError = True
_tryOnErrorResume.Add(node)
If node.OnErrorKind = OnErrorStatementKind.ResumeNext Then
_containsResume = True
If _resumeWithoutLabel Is Nothing Then
_resumeWithoutLabel = DirectCast(node.Syntax, StatementSyntax)
End If
End If
If _enclosingSyncLockOrUsing IsNot Nothing Then
ReportDiagnostic(_diagnostics, node.Syntax,
If(_enclosingSyncLockOrUsing.Kind = BoundKind.UsingStatement,
ERRID.ERR_OnErrorInUsing,
ERRID.ERR_OnErrorInSyncLock))
_reportedAnError = True
End If
Return Nothing
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Debug.Assert(Not node.WasCompilerGenerated)
_containsResume = True
If node.ResumeKind <> ResumeStatementKind.Label AndAlso _resumeWithoutLabel Is Nothing Then
_resumeWithoutLabel = DirectCast(node.Syntax, StatementSyntax)
End If
_tryOnErrorResume.Add(node)
Return Nothing
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Debug.Assert(Not node.WasCompilerGenerated)
Dim save = _enclosingSyncLockOrUsing
Dim save_m_isInCatchFinallyOrSyncLock As Boolean = _isInCatchFinallyOrSyncLock
_enclosingSyncLockOrUsing = node
_isInCatchFinallyOrSyncLock = True
MyBase.VisitSyncLockStatement(node)
_enclosingSyncLockOrUsing = save
_isInCatchFinallyOrSyncLock = save_m_isInCatchFinallyOrSyncLock
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Debug.Assert(Not node.WasCompilerGenerated)
Dim save = _enclosingSyncLockOrUsing
_enclosingSyncLockOrUsing = node
MyBase.VisitUsingStatement(node)
_enclosingSyncLockOrUsing = save
Return Nothing
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Debug.Assert(_binder.IsInAsyncContext())
_containsAwait = True
If _isInCatchFinallyOrSyncLock Then
ReportDiagnostic(_diagnostics, node.Syntax, ERRID.ERR_BadAwaitInTryHandler)
_reportedAnError = True
End If
Return MyBase.VisitAwaitOperator(node)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Debug.Assert(_binder.IsInAsyncContext())
' Do not dive into the lambdas.
Return Nothing
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
_containsCatch = True
Return MyBase.VisitCatchBlock(node)
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
If Not node.WasCompilerGenerated AndAlso node.Syntax.Kind = SyntaxKind.LabelStatement AndAlso
DirectCast(node.Syntax, LabelStatementSyntax).LabelToken.Kind = SyntaxKind.IntegerLiteralToken Then
_containsLineNumberLabel = True
End If
Return MyBase.VisitLabelStatement(node)
End Function
End Class
Private Shared Sub ReportNameConfictsBetweenStaticLocals(methodBlockBinder As Binder, diagnostics As DiagnosticBag)
Dim currentBinder As Binder = methodBlockBinder
Dim bodyBinder As MethodBodyBinder
Do
bodyBinder = TryCast(currentBinder, MethodBodyBinder)
If bodyBinder IsNot Nothing Then
Exit Do
End If
currentBinder = currentBinder.ContainingBinder
Loop While currentBinder IsNot Nothing
Debug.Assert(bodyBinder IsNot Nothing)
If bodyBinder IsNot Nothing Then
Dim staticLocals As Dictionary(Of String, ArrayBuilder(Of LocalSymbol)) = Nothing
For Each binder As BlockBaseBinder In bodyBinder.StmtListToBinderMap.Values
For Each local In binder.Locals
If local.IsStatic Then
Dim array As ArrayBuilder(Of LocalSymbol) = Nothing
If staticLocals Is Nothing Then
staticLocals = New Dictionary(Of String, ArrayBuilder(Of LocalSymbol))(CaseInsensitiveComparison.Comparer)
array = New ArrayBuilder(Of LocalSymbol)()
staticLocals.Add(local.Name, array)
ElseIf Not staticLocals.TryGetValue(local.Name, array) Then
array = New ArrayBuilder(Of LocalSymbol)()
staticLocals.Add(local.Name, array)
End If
array.Add(local)
End If
Next
Next
If staticLocals IsNot Nothing Then
For Each nameToArray In staticLocals
Dim array = nameToArray.Value
If array.Count > 1 Then
Dim lexicallyFirst As LocalSymbol = array(0)
For i As Integer = 1 To array.Count - 1
If lexicallyFirst.IdentifierToken.Position > array(i).IdentifierToken.Position Then
lexicallyFirst = array(i)
End If
Next
For Each local In array
If lexicallyFirst IsNot local Then
ReportDiagnostic(diagnostics, local.IdentifierToken, ERRID.ERR_DuplicateLocalStatic1, local.Name)
End If
Next
End If
Next
End If
End If
End Sub
''' <summary> Defines max allowed rank of the array </summary>
''' <remarks> Currently set to 32 because of COM+ array type limits </remarks>
Public Const ArrayRankLimit = 32
Private Function BindRedimStatement(node As ReDimStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim operands = ArrayBuilder(Of BoundRedimClause).GetInstance()
Dim hasPreserveClause = node.Kind = SyntaxKind.ReDimPreserveStatement
For Each redimOperand As RedimClauseSyntax In node.Clauses
Dim redimClauseHasErrors As Boolean = False
' bind operand expression as an assignment target
Dim redimTarget = BindAssignmentTarget(redimOperand.Expression, diagnostics)
If redimTarget.HasErrors Then
redimClauseHasErrors = True
End If
' check for validity of an assignment target, report diagnostics, discard the result
AdjustAssignmentTarget(redimOperand.Expression, redimTarget, diagnostics, redimClauseHasErrors)
' in case it is a Redim Preserve we will make an r-value of it in rewrite phase;
' in initial binding we report diagnostics, but throw away the result
If Not redimClauseHasErrors AndAlso hasPreserveClause Then
Dim temp = MakeRValue(redimTarget, diagnostics)
If temp.HasErrors Then
redimClauseHasErrors = True
End If
End If
' bind arguments/indices
Dim boundIndices As ImmutableArray(Of BoundExpression) = ImmutableArray(Of BoundExpression).Empty
If redimOperand.ArrayBounds IsNot Nothing Then
boundIndices = BindArrayBounds(redimOperand.ArrayBounds, diagnostics, errorOnEmptyBound:=True)
For Each arg In boundIndices
If arg.HasErrors Then
redimClauseHasErrors = True
End If
Next
End If
' check for the resulting type of the redim target expression: it should be either an array or an object
Dim arrayType As ArrayTypeSymbol = Nothing
If Not redimClauseHasErrors Then
Dim redimTargetType = redimTarget.Type
Debug.Assert(redimTargetType IsNot Nothing)
If redimTargetType.IsArrayType Then
arrayType = DirectCast(redimTargetType, ArrayTypeSymbol)
ElseIf redimTargetType.IsObjectType() Then
If boundIndices.Length > 0 Then ' missing redim size error will be reported later
arrayType = ArrayTypeSymbol.CreateVBArray(redimTargetType, Nothing, boundIndices.Length, Compilation)
End If
Else
ReportDiagnostic(diagnostics, redimOperand.Expression, ERRID.ERR_ExpectedArray1, "Redim")
redimClauseHasErrors = True
End If
End If
' check redim array rank
If Not redimClauseHasErrors Then
If boundIndices.Length = 0 Then
' redim rank cannot be 0
ReportDiagnostic(diagnostics, redimOperand, ERRID.ERR_RedimNoSizes)
redimClauseHasErrors = True
Else
' otherwise the number of indices should match the array rank
If arrayType.Rank <> boundIndices.Length Then
ReportDiagnostic(diagnostics, redimOperand, ERRID.ERR_RedimRankMismatch)
redimClauseHasErrors = True
End If
End If
End If
Debug.Assert(redimClauseHasErrors OrElse arrayType IsNot Nothing)
' check for an array rank limit value
If Not redimClauseHasErrors AndAlso boundIndices.Length > ArrayRankLimit Then
ReportDiagnostic(diagnostics, redimOperand, ERRID.ERR_ArrayRankLimit)
redimClauseHasErrors = True
End If
operands.Add(
New BoundRedimClause(
redimOperand,
redimTarget,
boundIndices,
arrayType,
hasPreserveClause,
redimClauseHasErrors)
)
Next
' done with all clauses, build a bound redim statement
Return New BoundRedimStatement(node, operands.ToImmutableAndFree())
End Function
Private Function BindEraseStatement(node As EraseStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim clauses = ArrayBuilder(Of BoundAssignmentOperator).GetInstance()
Dim nothingLiteral = New BoundLiteral(node, ConstantValue.Nothing, Nothing).MakeCompilerGenerated()
For Each operand As ExpressionSyntax In node.Expressions
Dim target As BoundExpression = BindAssignmentTarget(operand, diagnostics)
Debug.Assert(target IsNot Nothing)
Dim clause As BoundAssignmentOperator
If target.HasErrors Then
clause = New BoundAssignmentOperator(operand, target, nothingLiteral, False, target.Type, hasErrors:=True).MakeCompilerGenerated()
ElseIf Not target.Type.IsErrorType() AndAlso
Not target.Type.IsArrayType() AndAlso
target.Type.SpecialType <> SpecialType.System_Array AndAlso
target.Type.SpecialType <> SpecialType.System_Object Then
ReportDiagnostic(diagnostics, operand, ERRID.ERR_ExpectedArray1, "Erase")
clause = New BoundAssignmentOperator(operand, target, nothingLiteral, False, target.Type, hasErrors:=True).MakeCompilerGenerated()
Else
clause = BindAssignment(operand, target,
ApplyImplicitConversion(operand, target.Type, nothingLiteral, diagnostics).MakeCompilerGenerated(),
diagnostics).MakeCompilerGenerated()
End If
clauses.Add(clause)
Next
Return New BoundEraseStatement(node, clauses.ToImmutableAndFree())
End Function
Private Function BindGoToStatement(node As GoToStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim symbol As LabelSymbol = Nothing
Dim boundLabelExpression As BoundExpression = BindExpression(node.Label, diagnostics)
If boundLabelExpression.Kind = BoundKind.Label Then
Dim boundLabel = DirectCast(boundLabelExpression, boundLabel)
symbol = boundLabel.Label
Dim hasErrors As Boolean = boundLabel.HasErrors
' Found label now verify that it is OK to jump to the location.
hasErrors = hasErrors OrElse
Not IsValidLabelForGoto(symbol, node.Label, diagnostics)
Return New BoundGotoStatement(node, symbol, boundLabel, hasErrors:=hasErrors)
Else
' if the bound label is e.g. a bad bound expression because of a non-existent label,
' make this a bad statement.
Return New BoundBadStatement(node, ImmutableArray.Create(Of BoundNode)(boundLabelExpression), hasErrors:=True)
End If
End Function
Private Function IsValidLabelForGoto(label As LabelSymbol, labelSyntax As LabelSyntax, diagnostics As DiagnosticBag) As Boolean
Dim hasError As Boolean = False
Dim labelParent = DirectCast(label.LabelName.Parent, VisualBasicSyntaxNode)
' Determine if the reference is a branch that crosses
' into a Try/Catch/Finally or With statement.
' once a method or lambda block is found we can stop searching
Dim errorID = ERRID.ERR_None
While labelParent IsNot Nothing
Select Case labelParent.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Exit While
Case SyntaxKind.TryBlock,
SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
errorID = ERRID.ERR_GotoIntoTryHandler
Case SyntaxKind.UsingBlock
errorID = ERRID.ERR_GotoIntoUsing
Case SyntaxKind.SyncLockBlock
errorID = ERRID.ERR_GotoIntoSyncLock
Case SyntaxKind.WithBlock
errorID = ERRID.ERR_GotoIntoWith
Case SyntaxKind.ForBlock,
SyntaxKind.ForEachBlock
errorID = ERRID.ERR_GotoIntoFor
End Select
If errorID <> ERRID.ERR_None Then
If Not IsValidBranchTarget(labelParent, labelSyntax) Then
ReportDiagnostic(diagnostics, labelSyntax, ErrorFactory.ErrorInfo(errorID, label.Name))
hasError = True
End If
Exit While
End If
labelParent = labelParent.Parent
End While
Return Not hasError
End Function
Private Shared Function IsValidBranchTarget(block As VisualBasicSyntaxNode, labelSyntax As LabelSyntax) As Boolean
Debug.Assert(block.Kind = SyntaxKind.TryBlock OrElse
block.Kind = SyntaxKind.CatchBlock OrElse
block.Kind = SyntaxKind.FinallyBlock OrElse
block.Kind = SyntaxKind.UsingBlock OrElse
block.Kind = SyntaxKind.SyncLockBlock OrElse
block.Kind = SyntaxKind.WithBlock OrElse
block.Kind = SyntaxKind.ForBlock OrElse
block.Kind = SyntaxKind.ForEachBlock)
Dim parent = labelSyntax.Parent
While parent IsNot Nothing
If parent Is block Then
Return True
End If
parent = parent.Parent
End While
Return False
End Function
Private Function BindLabelStatement(node As LabelStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim labelToken As SyntaxToken = node.LabelToken
Dim labelName = labelToken.ValueText
' A label symbol will always be found because all labels without syntax errors are put into the
' label map in the blockbasebinder.
Dim result = LookupResult.GetInstance()
Lookup(result, labelName, 0, LookupOptions.LabelsOnly, useSiteDiagnostics:=Nothing)
Debug.Assert(result.HasSingleSymbol AndAlso result.IsGood)
Dim symbol = DirectCast(result.SingleSymbol, SourceLabelSymbol)
' Check for duplicate goto label
Dim hasError = False
If symbol.LabelName <> labelToken Then
' If symbol's token does not match the node's token then this is not the label target but a duplicate definition
ReportDiagnostic(diagnostics, labelToken, ERRID.ERR_MultiplyDefined1, labelName)
hasError = True
End If
result.Free()
Return New BoundLabelStatement(node, symbol, hasErrors:=hasError)
End Function
''' <summary>
''' Decodes a set of local declaration modifier flags and reports any errors with the flags.
''' </summary>
''' <param name="syntax">The syntax list of the modifiers.</param>
''' <param name="diagBag">returns True if any errors are reported</param>
Private Sub DecodeLocalModifiersAndReportErrors(syntax As SyntaxTokenList, diagBag As DiagnosticBag)
Const localModifiersMask = SourceMemberFlags.Const Or SourceMemberFlags.Dim Or SourceMemberFlags.Static
Dim foundModifiers As SourceMemberFlags = Nothing
' Go through each modifiers, accumulating flags of what we've seen and reporting errors.
Dim firstDim As SyntaxToken = Nothing
Dim firstStatic As SyntaxToken = Nothing
For Each keywordSyntax In syntax
Dim currentModifier As SourceMemberFlags = MapKeywordToFlag(keywordSyntax)
If currentModifier = SourceMemberFlags.None Then
Continue For
End If
' Report errors with the modifier
If (currentModifier And localModifiersMask) = 0 Then
ReportDiagnostic(diagBag, keywordSyntax, ERRID.ERR_BadLocalDimFlags1, keywordSyntax.ToString())
ElseIf (currentModifier And foundModifiers) <> 0 Then
ReportDiagnostic(diagBag, keywordSyntax, ERRID.ERR_DuplicateSpecifier)
Else
Select Case currentModifier
Case SourceMemberFlags.Dim
firstDim = keywordSyntax
Case SourceMemberFlags.Static
firstStatic = keywordSyntax
End Select
foundModifiers = foundModifiers Or currentModifier
End If
Next
If (foundModifiers And SourceMemberFlags.Const) <> 0 Then
' Const incompatible with Dim or Static
If (foundModifiers And SourceMemberFlags.Dim) <> 0 Then
ReportDiagnostic(diagBag, firstDim, ERRID.ERR_BadLocalConstFlags1, firstDim.ToString())
ElseIf (foundModifiers And SourceMemberFlags.Static) <> 0 Then
ReportDiagnostic(diagBag, firstStatic, ERRID.ERR_BadLocalConstFlags1, firstStatic.ToString())
End If
ElseIf (foundModifiers And SourceMemberFlags.Static) <> 0 Then
' 'Static' keyword is only allowed in class methods, but not in structure methods
If Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.TypeKind = TYPEKIND.Structure Then
' Local variables within methods of structures cannot be declared 'Static'
ReportDiagnostic(diagBag, firstStatic, ERRID.ERR_BadStaticLocalInStruct)
ElseIf Me.IsInLambda Then
ReportDiagnostic(diagBag, firstStatic, ERRID.ERR_StaticInLambda)
ElseIf Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).IsGenericMethod Then
ReportDiagnostic(diagBag, firstStatic, ERRID.ERR_BadStaticLocalInGenericMethod)
End If
End If
End Sub
Private Function BindLocalDeclaration(node As LocalDeclarationStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
DecodeLocalModifiersAndReportErrors(node.Modifiers, diagnostics)
Dim boundLocalDeclarations As ImmutableArray(Of BoundLocalDeclarationBase) = BindVariableDeclarators(node.Declarators, diagnostics)
' NOTE: Always create bound Dim statement to make
' sure syntax node has a bound node associated with it
Return New BoundDimStatement(node, boundLocalDeclarations, Nothing)
End Function
Private Function BindVariableDeclarators(
declarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax),
diagnostics As DiagnosticBag
) As ImmutableArray(Of BoundLocalDeclarationBase)
Dim builder = ArrayBuilder(Of BoundLocalDeclarationBase).GetInstance()
For Each varDecl In declarators
Dim asClauseOpt = varDecl.AsClause
Dim initializerOpt As EqualsValueSyntax = varDecl.Initializer
If initializerOpt IsNot Nothing Then
If varDecl.Names.Count > 1 Then
' Can't combine an initializer with multiple variables
ReportDiagnostic(diagnostics, varDecl, ERRID.ERR_InitWithMultipleDeclarators)
End If
End If
Dim names = varDecl.Names
Dim asNewVariablePlaceholder As BoundWithLValueExpressionPlaceholder = Nothing
If names.Count = 1 Then
' Dim x as integer = 1 OR Dim x as New Integer
builder.Add(BindVariableDeclaration(varDecl, names(0), asClauseOpt, initializerOpt, diagnostics))
ElseIf asClauseOpt Is Nothing OrElse asClauseOpt.Kind <> SyntaxKind.AsNewClause Then
' Dim x,y,z as integer
For i = 0 To names.Count - 1
Dim var = BindVariableDeclaration(varDecl, names(i), asClauseOpt, If(i = names.Count - 1, initializerOpt, Nothing), diagnostics)
builder.Add(var)
Next
Else
' Dim x,y,z as New C
Dim nameCount = names.Count
Dim locals = ArrayBuilder(Of BoundLocalDeclaration).GetInstance(nameCount)
For i = 0 To nameCount - 1
' Pass the asClause to each local declaration so local knows its type and for error reporting.
Dim var = BindVariableDeclaration(varDecl, names(i), asClauseOpt, Nothing, diagnostics, i > 0)
locals.Add(var)
Next
' At this point all of the local declarations have an initializer. Remove the initializers from the individual local declarations
' and put the initializer on the BoundAsNewDeclaration. The local declarations are marked as initialized by the as-new.
Dim var0 As BoundLocalDeclaration = locals(0)
Dim asNewInitializer = var0.InitializerOpt
locals(0) = var0.Update(var0.LocalSymbol, Nothing, True)
#If DEBUG Then
For i = 0 To names.Count - 1
Debug.Assert(locals(i).InitializedByAsNew)
Debug.Assert(locals(i).InitializerOpt Is Nothing OrElse locals(i).InitializerOpt.Kind = BoundKind.BadExpression)
Next
#End If
builder.Add(New BoundAsNewLocalDeclarations(varDecl, locals.ToImmutableAndFree(), asNewInitializer))
End If
Next
Return builder.ToImmutableAndFree()
End Function
Private Function GetLocalForDeclaration(identifier As SyntaxToken) As LocalSymbol
' We cannot rely on lookup to find the local because there could be locals with duplicate names.
Dim current As Binder = Me
Dim blockBinder As BlockBaseBinder
Do
blockBinder = TryCast(current, BlockBaseBinder)
If blockBinder IsNot Nothing Then
Exit Do
End If
current = current.ContainingBinder
Loop
For Each local In blockBinder.Locals
If local.IdentifierToken = identifier Then
Return local
End If
Next
Throw ExceptionUtilities.Unreachable
End Function
Friend Overridable Function BindVariableDeclaration(
tree As VisualBasicSyntaxNode,
name As ModifiedIdentifierSyntax,
asClauseOpt As AsClauseSyntax,
equalsValueOpt As EqualsValueSyntax,
diagnostics As DiagnosticBag,
Optional skipAsNewInitializer As Boolean = False
) As BoundLocalDeclaration
Dim symbol As LocalSymbol = GetLocalForDeclaration(name.Identifier)
Dim valueExpression As BoundExpression = Nothing
Dim declType As TypeSymbol = Nothing
Dim boundArrayBounds As ImmutableArray(Of BoundExpression) = Nothing
If name.ArrayBounds IsNot Nothing Then
' So as not to trigger order of simple name binding checks, must bind array bounds before initializer.
boundArrayBounds = BindArrayBounds(name.ArrayBounds, diagnostics)
End If
' We don't bind the value here and pass it into ComputeVariableType because there is a chicken and egg problem.
' If the symbol has a type either from the type character or the as clause then we must first set the symbol
' to that type before binding the expression. For example,
'
' Dim i% = i
' is valid. If "i" were bound before the "i%" was resolved then i would not have a type and the expression
' would have an error. ComputeVariableType will only bind the value if the symbol does not have an explicit
' type.
Dim type As TypeSymbol = ComputeVariableType(symbol,
name,
asClauseOpt,
equalsValueOpt,
valueExpression,
declType,
diagnostics)
' Now that we know the type go ahead and set it.
VerifyLocalSymbolNameAndSetType(symbol, type, name, name.Identifier, diagnostics)
Debug.Assert(type IsNot Nothing)
Dim isInitializedByAsNew As Boolean = asClauseOpt IsNot Nothing AndAlso asClauseOpt.Kind = SyntaxKind.AsNewClause
Dim errSyntax = If(asClauseOpt Is Nothing, DirectCast(equalsValueOpt, VisualBasicSyntaxNode), asClauseOpt.Type)
Dim restrictedType As TypeSymbol = Nothing
If type.IsRestrictedArrayType(restrictedType) Then
If Not isInitializedByAsNew OrElse Not skipAsNewInitializer Then
ReportDiagnostic(diagnostics, errSyntax, ERRID.ERR_RestrictedType1, restrictedType)
End If
ElseIf symbol.IsStatic Then
If type.IsRestrictedType() Then
If Not isInitializedByAsNew OrElse Not skipAsNewInitializer Then
ReportDiagnostic(diagnostics, errSyntax, ERRID.ERR_RestrictedType1, type)
End If
ElseIf IsInAsyncContext() OrElse IsInIteratorContext() Then
ReportDiagnostic(diagnostics, name, ERRID.ERR_BadStaticInitializerInResumable)
End If
ElseIf IsInAsyncContext() OrElse IsInIteratorContext() Then
If type.IsRestrictedType() Then
If Not isInitializedByAsNew OrElse Not skipAsNewInitializer Then
ReportDiagnostic(diagnostics, errSyntax, ERRID.ERR_CannotLiftRestrictedTypeResumable1, type)
End If
End If
End If
If valueExpression Is Nothing Then
' We computed the type without needing to do type inference so bind the expression now.
' Because this symbol has a type, there is no danger of infinite recursion so we don't need
' a special binder.
If symbol.IsConst Then
valueExpression = symbol.GetConstantExpression(Me)
ElseIf equalsValueOpt IsNot Nothing Then
Dim valueSyntax = equalsValueOpt.Value
valueExpression = BindValue(valueSyntax, diagnostics)
End If
End If
If valueExpression IsNot Nothing AndAlso Not symbol.IsConst Then
' Only apply the conversion for non constants. Conversions for constants are handled in GetConstantExpression.
valueExpression = ApplyImplicitConversion(valueExpression.Syntax, type, valueExpression, diagnostics)
End If
If isInitializedByAsNew Then
Dim asNew = DirectCast(asClauseOpt, AsNewClauseSyntax)
If symbol.IsConst Then
ReportDiagnostic(diagnostics, asNew.NewExpression.NewKeyword, ERRID.ERR_BadLocalConstFlags1, asNew.NewExpression.NewKeyword.ToString())
Else
' If there is an AsNew clause then create the object as well.
Select Case asNew.NewExpression.Kind
Case SyntaxKind.ObjectCreationExpression
Debug.Assert(valueExpression Is Nothing)
If Not skipAsNewInitializer Then
Dim objectCreationExpressionSyntax = DirectCast(asNew.NewExpression, objectCreationExpressionSyntax)
Dim asNewVariablePlaceholder As New BoundWithLValueExpressionPlaceholder(asClauseOpt, symbol.Type)
asNewVariablePlaceholder.SetWasCompilerGenerated()
valueExpression = BindObjectCreationExpression(asNew.Type,
objectCreationExpressionSyntax.ArgumentList,
declType,
objectCreationExpressionSyntax,
diagnostics,
asNewVariablePlaceholder)
Debug.Assert(valueExpression.Type.IsSameTypeIgnoringAll(declType))
End If
Case SyntaxKind.AnonymousObjectCreationExpression
' Is supposed to be already bound by ComputeVariableType
Debug.Assert(valueExpression IsNot Nothing)
Case Else
Throw ExceptionUtilities.UnexpectedValue(asNew.NewExpression.Kind)
End Select
If type.IsArrayType Then
' Arrays cannot be declared with AsNew syntax
ReportDiagnostic(diagnostics, asNew.NewExpression.NewKeyword, ERRID.ERR_AsNewArray)
valueExpression = BadExpression(asNew, valueExpression, type)
ElseIf valueExpression IsNot Nothing AndAlso Not valueExpression.HasErrors AndAlso
Not type.IsSameTypeIgnoringAll(valueExpression.Type) Then
' An error must have been reported elsewhere.
valueExpression = BadExpression(asNew, valueExpression, valueExpression.Type)
End If
End If
End If
If name.ArrayBounds IsNot Nothing Then
' It is an error to have both array bounds and an initializer expression
If valueExpression IsNot Nothing Then
If Not isInitializedByAsNew Then
ReportDiagnostic(diagnostics, name, ERRID.ERR_InitWithExplicitArraySizes)
Else
' Must have reported ERR_AsNewArray already.
Debug.Assert(valueExpression.Kind = BoundKind.BadExpression)
End If
Else
valueExpression = New BoundArrayCreation(name, boundArrayBounds, Nothing, type)
End If
End If
If symbol.IsConst Then
If Not type.IsErrorType() Then
If Not type.IsValidTypeForConstField() Then
' "Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type."
' arrays get the squiggles under the identifier name
' other data types get the squiggles under the type part of the as clause
errSyntax = If(asClauseOpt IsNot Nothing AndAlso Not type.IsArrayType, DirectCast(asClauseOpt.Type, VisualBasicSyntaxNode), name)
ReportDiagnostic(diagnostics, errSyntax, ERRID.ERR_ConstAsNonConstant)
Else
Dim bag = symbol.GetConstantValueDiagnostics(Me)
If bag IsNot Nothing Then
diagnostics.AddRange(bag)
End If
End If
End If
End If
Return New BoundLocalDeclaration(name, symbol, valueExpression, isInitializedByAsNew)
End Function
''' <summary>
''' Compute the type of a local symbol using the type character, as clause and equals value expression.
''' 1. Try to compute the type based on the identifier/modified identifier and as clause. If there is a type then we're done.
''' 2. If OptionInfer is on then evaluate the expression and use that to infer the type.
'''
''' ComputeVariableType will only bind the value if the symbol does not have an explicit type.
''' </summary>
''' <param name="symbol">The local symbol</param>
''' <param name="modifiedIdentifierOpt">The symbols modified identifier is there is one</param>
''' <param name="asClauseOpt">The optional as clause</param>
''' <param name="equalsValueOpt">The optional initializing expression</param>
''' <param name="valueExpression">The bound initializing expression</param>
''' <param name="asClauseType">The bound as clause type</param>
Friend Function ComputeVariableType(symbol As LocalSymbol,
modifiedIdentifierOpt As ModifiedIdentifierSyntax,
asClauseOpt As AsClauseSyntax,
equalsValueOpt As EqualsValueSyntax,
<Out()> ByRef valueExpression As BoundExpression,
<Out()> ByRef asClauseType As TypeSymbol,
diagnostics As DiagnosticBag) As TypeSymbol
valueExpression = Nothing
Dim typeDiagnostic As Func(Of DiagnosticInfo) = Nothing
If symbol.IsStatic Then
If OptionStrict = OptionStrict.On Then
typeDiagnostic = ErrorFactory.GetErrorInfo_ERR_StrictDisallowImplicitObject
ElseIf OptionStrict = OptionStrict.Custom Then
typeDiagnostic = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_StaticLocalNoInference
End If
ElseIf Not (OptionInfer AndAlso equalsValueOpt IsNot Nothing) Then
If OptionStrict = OptionStrict.On Then
typeDiagnostic = ErrorFactory.GetErrorInfo_ERR_StrictDisallowImplicitObject
ElseIf OptionStrict = OptionStrict.Custom Then
typeDiagnostic = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl
End If
End If
Dim type As TypeSymbol
Dim hasExplicitType As Boolean
If modifiedIdentifierOpt IsNot Nothing Then
If asClauseOpt IsNot Nothing AndAlso asClauseOpt.Kind = SyntaxKind.AsNewClause Then
Dim asNewClause = DirectCast(asClauseOpt, AsNewClauseSyntax)
Dim newExpression As NewExpressionSyntax = asNewClause.NewExpression
Debug.Assert(newExpression IsNot Nothing)
If newExpression.Kind = SyntaxKind.AnonymousObjectCreationExpression Then
' Bind anonymous type creation to define it's type
Dim binder = New LocalInProgressBinder(Me, symbol)
valueExpression = binder.BindAnonymousObjectCreationExpression(
DirectCast(newExpression, AnonymousObjectCreationExpressionSyntax), diagnostics)
asClauseType = valueExpression.Type
Return asClauseType
End If
End If
' Adjust type because the modified identifier can change the type to array or make it nullable.
' DecodeModifiedIdentifierType returns the explicit type or the default type based on object. i.e. object or object()
type = DecodeModifiedIdentifierType(modifiedIdentifierOpt, asClauseOpt, equalsValueOpt,
typeDiagnostic,
asClauseType,
diagnostics,
If(symbol.IsStatic,
ModifiedIdentifierTypeDecoderContext.StaticLocalType Or ModifiedIdentifierTypeDecoderContext.LocalType,
ModifiedIdentifierTypeDecoderContext.LocalType))
hasExplicitType = Not HasDefaultType(modifiedIdentifierOpt, asClauseOpt)
Else
Dim identifier = symbol.IdentifierToken
type = DecodeIdentifierType(identifier, asClauseOpt,
typeDiagnostic,
asClauseType,
diagnostics)
hasExplicitType = Not HasDefaultType(identifier, asClauseOpt)
End If
If hasExplicitType AndAlso Not (symbol.IsConst AndAlso type.SpecialType = SpecialType.System_Object) Then
' There is an explicit type or TypeCharacter. Return the type.
' Constants are special. Don't return here when a constant is typed as object.
Return type
End If
' The default type is Object. Infer a type if OptionInfer is on.
' Don't infer types for static locals.
' Always infer type of constant.
If OptionInfer AndAlso Not symbol.IsStatic AndAlso Not symbol.IsConst Then
If equalsValueOpt IsNot Nothing Then
Dim valueSyntax As ExpressionSyntax = equalsValueOpt.Value
' Use an LocalInProgressBinder to detect cycles using locals.
Dim binder = New LocalInProgressBinder(Me, symbol)
valueExpression = binder.BindValue(valueSyntax, diagnostics)
Dim inferFrom As BoundExpression = valueExpression
' Dig through parenthesized in case this expression is one of the special expressions
' that does not have a type such as lambda's and array literals.
If Not inferFrom.IsNothingLiteral Then
inferFrom = inferFrom.GetMostEnclosedParenthesizedExpression()
End If
Dim inferredType As TypeSymbol = Nothing
Dim arrayLiteral As BoundArrayLiteral = Nothing
Select Case inferFrom.Kind
Case BoundKind.UnboundLambda
inferredType = DirectCast(inferFrom, UnboundLambda).InferredAnonymousDelegate.Key
Case BoundKind.ArrayLiteral
arrayLiteral = DirectCast(inferFrom, BoundArrayLiteral)
inferredType = arrayLiteral.InferredType
Case BoundKind.TupleLiteral
Dim tupleLiteral = DirectCast(inferFrom, BoundTupleLiteral)
inferredType = tupleLiteral.InferredType
Case Else
inferredType = inferFrom.Type
End Select
If inferredType IsNot Nothing Then
' Infer the type from the expression. When the identifier has modifiers, the expression type
' and the modifiers need to be compatible. Without modifiers just use the expression type.
Dim localDiagnostics As DiagnosticBag = If(inferFrom.HasErrors, New DiagnosticBag(), diagnostics)
If modifiedIdentifierOpt IsNot Nothing Then
type = InferVariableType(type, modifiedIdentifierOpt, valueSyntax, inferredType, inferFrom, typeDiagnostic, localDiagnostics)
If type IsNot inferredType AndAlso arrayLiteral IsNot Nothing Then
' Normally ReportArrayLiteralInferredElementTypeDiagnostics is handled in ReclassifyArrayLiteralExpression.
' ReportArrayLiteralInferredElementTypeDiagnostics depends on being able to compare the variable type with
' the inferred type. When the symbols are the same, it assumes the variable got its type from the expression.
' Because the modified identifier created a new array type symbol, we report errors now.
ReportArrayLiteralInferredTypeDiagnostics(arrayLiteral, localDiagnostics)
End If
Else
type = inferredType
End If
End If
End If
ElseIf symbol.IsConst Then
' If we arrive here it is because the constant does not have an explicit type or the type is object.
' In either case, the type will always be the type of the expression.
valueExpression = symbol.GetConstantExpression(Me)
Dim valueType = valueExpression.Type
If valueType IsNot Nothing AndAlso valueType.GetEnumUnderlyingTypeOrSelf.IsIntrinsicType Then
type = valueExpression.Type
End If
ElseIf Not symbol.IsStatic AndAlso OptionStrict <> OptionStrict.On AndAlso
Not hasExplicitType AndAlso type.IsObjectType() AndAlso
modifiedIdentifierOpt IsNot Nothing AndAlso
modifiedIdentifierOpt.Nullable.Node IsNot Nothing AndAlso
equalsValueOpt IsNot Nothing Then
Debug.Assert(Not symbol.IsConst AndAlso Not symbol.IsStatic AndAlso Not OptionInfer)
ReportDiagnostic(diagnostics, modifiedIdentifierOpt, ERRID.ERR_NullableTypeInferenceNotSupported)
End If
' Return the inferred type or the default type
Return type
End Function
''' <summary>
''' Infer the type of a for-from-to control variable.
''' </summary>
Friend Function InferForFromToVariableType(symbol As LocalSymbol,
fromValueSyntax As ExpressionSyntax,
toValueSyntax As ExpressionSyntax,
stepClauseSyntaxOpt As ForStepClauseSyntax,
<Out()> ByRef fromValueExpression As BoundExpression,
<Out()> ByRef toValueExpression As BoundExpression,
<Out()> ByRef stepValueExpression As BoundExpression,
diagnostics As DiagnosticBag) As TypeSymbol
fromValueExpression = Nothing
toValueExpression = Nothing
stepValueExpression = Nothing
Dim identifier = symbol.IdentifierToken
Dim type = DecodeIdentifierType(identifier, Nothing,
Nothing,
Nothing,
diagnostics)
Dim hasExplicitType = Not HasDefaultType(identifier, Nothing)
If hasExplicitType Then
Return type
End If
' Use an ImplicitlyTypedLocalBinder to detect cycles using locals.
Dim binder = New LocalInProgressBinder(Me, symbol)
fromValueExpression = binder.BindRValue(fromValueSyntax, diagnostics)
toValueExpression = binder.BindRValue(toValueSyntax, diagnostics)
If stepClauseSyntaxOpt IsNot Nothing Then
stepValueExpression = binder.BindRValue(stepClauseSyntaxOpt.StepValue, diagnostics)
End If
If toValueExpression.HasErrors OrElse fromValueExpression.HasErrors OrElse
(stepValueExpression IsNot Nothing AndAlso stepValueExpression.HasErrors) Then
Return type
End If
Dim numCandidates As Integer = 0
Dim array = ArrayBuilder(Of BoundExpression).GetInstance(2)
array.Add(fromValueExpression)
array.Add(toValueExpression)
If stepValueExpression IsNot Nothing Then
array.Add(stepValueExpression)
End If
Dim identifierName = DirectCast(identifier.Parent, IdentifierNameSyntax)
Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
Dim dominantType = InferDominantTypeOfExpressions(identifierName, array, diagnostics, numCandidates, errorReasons)
array.Free()
' check the resulting type
If numCandidates = 0 OrElse (numCandidates > 1 AndAlso (errorReasons And InferenceErrorReasons.Ambiguous) = 0) Then
ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_NoSuitableWidestType1, identifierName.Identifier.ValueText)
Return type
ElseIf numCandidates > 1 Then
ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_AmbiguousWidestType3, identifierName.Identifier.ValueText)
Return type
End If
If dominantType IsNot Nothing Then
Return dominantType
End If
Return type
End Function
''' <summary>
''' Infer the type of a for-each control variable.
''' </summary>
Friend Function InferForEachVariableType(symbol As LocalSymbol,
collectionSyntax As ExpressionSyntax,
<Out()> ByRef collectionExpression As BoundExpression,
<Out()> ByRef currentType As TypeSymbol,
<Out()> ByRef isEnumerable As Boolean,
<Out()> ByRef boundGetEnumeratorCall As BoundExpression,
<Out()> ByRef boundEnumeratorPlaceholder As BoundLValuePlaceholder,
<Out()> ByRef boundMoveNextCall As BoundExpression,
<Out()> ByRef boundCurrentAccess As BoundExpression,
<Out()> ByRef collectionPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef needToDispose As Boolean,
<Out()> ByRef isOrInheritsFromOrImplementsIDisposable As Boolean,
diagnostics As DiagnosticBag) As TypeSymbol
collectionExpression = Nothing
currentType = Nothing
isEnumerable = False
boundGetEnumeratorCall = Nothing
boundEnumeratorPlaceholder = Nothing
boundMoveNextCall = Nothing
boundCurrentAccess = Nothing
collectionPlaceholder = Nothing
needToDispose = False
isOrInheritsFromOrImplementsIDisposable = False
Dim identifier = symbol.IdentifierToken
Dim type = DecodeIdentifierType(identifier, Nothing,
Nothing,
Nothing,
diagnostics)
Dim hasExplicitType = Not HasDefaultType(identifier, Nothing)
If hasExplicitType Then
Return type
End If
' Use an ImplicitlyTypedLocalBinder to detect cycles using locals.
Dim binder = New LocalInProgressBinder(Me, symbol)
' bind the expression that describes the collection to iterate over
collectionExpression = binder.BindValue(collectionSyntax, diagnostics)
' collection will be a target to a GetEnumerator call, so we need to adjust
' it to RValue if it is not an LValue already.
If Not collectionExpression.IsLValue AndAlso Not collectionExpression.IsNothingLiteral Then
collectionExpression = MakeRValue(collectionExpression, diagnostics)
End If
Dim unconvertedCollectionType = collectionExpression.Type
' check if the collection is valid for a for each
collectionExpression = InterpretForEachStatementCollection(collectionExpression,
currentType,
isEnumerable,
boundGetEnumeratorCall,
boundEnumeratorPlaceholder,
boundMoveNextCall,
boundCurrentAccess,
collectionPlaceholder,
needToDispose,
isOrInheritsFromOrImplementsIDisposable,
diagnostics)
If Not collectionExpression.HasErrors AndAlso Not currentType.IsErrorType Then
' currentType may be "Object" because it's basically the return type of the "Current"
' property. If it's an array type the inferred local type should be the element type.
If collectionExpression.Type.IsArrayType Then
Return DirectCast(collectionExpression.Type, ArrayTypeSymbol).ElementType
ElseIf unconvertedCollectionType IsNot Nothing AndAlso unconvertedCollectionType.IsStringType Then
' Reproduce dev11 behavior: we're always going to lower a foreach loop over a string to a for loop
' over the string's Chars indexer. Therefore, we should infer "char", regardless of what the spec
' indicates the element type is. This actually matters in practice because the System.String in
' the portable library doesn't have a pattern GetEnumerator method or implement IEnumerable(Of char).
Return GetSpecialType(SpecialType.System_Char, collectionExpression.Syntax, diagnostics)
Else
Return currentType
End If
End If
Return type
End Function
''' <summary>
''' Infer the type of a variable declared with an initializing expression.
''' </summary>
Private Function InferVariableType(defaultType As TypeSymbol,
name As ModifiedIdentifierSyntax,
valueSyntax As ExpressionSyntax,
valueType As TypeSymbol,
valueExpression As BoundExpression,
getRequireTypeDiagnosticInfoFunc As Func(Of DiagnosticInfo),
diagnostics As DiagnosticBag) As TypeSymbol
Dim nameIsArrayType = IsArrayType(name)
Dim nameHasNullable = name.Nullable.Node IsNot Nothing
Dim identifier = name.Identifier
If nameHasNullable AndAlso
valueType.IsArrayType AndAlso
Not nameIsArrayType Then
' if name is nullable and expression is an array then the name must also be an array
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_CannotInferNullableForVariable1, name.Identifier.ToString())
ElseIf nameIsArrayType AndAlso Not valueType.IsArrayType Then
' if name is an array then the expression must be an array
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_InferringNonArrayType1, valueType)
ElseIf Not nameIsArrayType Then
If nameHasNullable Then
' name is nullable but not an array therefore the value must be a value type.
If Not valueType.IsValueType Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_CannotInferNullableForVariable1, identifier.ToString())
ElseIf valueType.IsNullableType Then
Return valueType
Else
Dim modifiedValueType = DecodeModifiedIdentifierType(name,
valueType,
Nothing,
valueSyntax,
getRequireTypeDiagnosticInfoFunc,
diagnostics)
Return modifiedValueType
End If
Else
' name does not add array or nullable so return the expression type.
Return valueType
End If
Else
Debug.Assert(nameIsArrayType AndAlso valueType.IsArrayType, "both the name and the value should be arrays")
' Both the name and the expression are arrays
' Check that the name's array is compatible with the expression array type
If nameHasNullable Then
' Verify that the rhs element type is also a nullable type
Dim rhsElementType As TypeSymbol = DirectCast(valueType, ArrayTypeSymbol).ElementType
Do
If Not rhsElementType.IsArrayType Then
Exit Do
End If
rhsElementType = DirectCast(rhsElementType, ArrayTypeSymbol).ElementType
Loop
If Not rhsElementType.IsNullableType Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_CannotInferNullableForVariable1, identifier.ToString())
Return defaultType
End If
End If
If DirectCast(defaultType, ArrayTypeSymbol).Rank <> DirectCast(valueType, ArrayTypeSymbol).Rank Then
Dim arrayLiteral = TryCast(valueExpression, BoundArrayLiteral)
' Arrays on both sides but ranks are not the same. This is an error unless rhs is an empty literal.
If (arrayLiteral Is Nothing OrElse Not arrayLiteral.IsEmptyArrayLiteral) Then
ReportDiagnostic(diagnostics, name, ERRID.ERR_TypeInferenceArrayRankMismatch1, name.Identifier.ToString())
End If
Else
' For arrays, if both the LHS and RHS specify an array shape, we
' have to allow inference to infer "arrays" when possible. That is, if
' we consider matching the shape from left to right, if we "consume" the arrays
' of the RHS and have "extra" arrays left over, we infer that.
'
' For example:
' dim x() = new Integer()() - we infer integer()()
' dim x(,)() = new Integer(,)()(,) - we infer integer(,)()(,)
'
' The algorithm used is to match the array rank until we exhaust the LHS,
' and if the RHS has more arrays, simply infer the RHS into the LHS. If the RHS
' "runs out of arrays" before the LHS, then we just infer the base type and give
' a conversion error.
Dim lhsType As TypeSymbol = defaultType
Dim rhsType As TypeSymbol = valueType
Do
If lhsType.IsArrayType AndAlso rhsType.IsArrayType Then
Dim lhsArrayType = DirectCast(lhsType, ArrayTypeSymbol)
Dim rhsArrayType = DirectCast(rhsType, ArrayTypeSymbol)
If lhsArrayType.Rank = rhsArrayType.Rank Then
lhsType = lhsArrayType.ElementType
rhsType = rhsArrayType.ElementType
Else
Exit Do
End If
ElseIf rhsType.IsArrayType OrElse Not lhsType.IsArrayType Then
Return valueType
Else
Exit Do
End If
Loop
Dim modifiedValueType = DecodeModifiedIdentifierType(name,
rhsType,
Nothing,
valueSyntax,
getRequireTypeDiagnosticInfoFunc,
diagnostics)
Return modifiedValueType
End If
End If
Return defaultType
End Function
'TODO: override in MethodBodySemanticModel similarly to BindVariableDeclaration.
Friend Overridable Function BindCatchVariableDeclaration(name As IdentifierNameSyntax,
asClause As AsClauseSyntax,
diagnostics As DiagnosticBag) As BoundLocal
Dim identifier = name.Identifier
Dim symbol As LocalSymbol = GetLocalForDeclaration(identifier)
' Attempt to bind the type
Dim type As TypeSymbol = BindTypeSyntax(asClause.Type, diagnostics)
VerifyLocalSymbolNameAndSetType(symbol, type, name, identifier, diagnostics)
Return New BoundLocal(name, symbol, symbol.Type)
End Function
''' <summary>
''' Verifies that declaration of a local symbol does not cause name clashes.
''' </summary>
Private Sub VerifyLocalSymbolNameAndSetType(local As LocalSymbol,
type As TypeSymbol,
nameSyntax As VisualBasicSyntaxNode,
identifier As SyntaxToken,
diagnostics As DiagnosticBag)
Dim localForFunctionValue = GetLocalForFunctionValue()
Dim name = identifier.ValueText
' Set the type of the symbol, so we don't have to re-compute it later.
local.SetType(type)
If localForFunctionValue IsNot Nothing AndAlso CaseInsensitiveComparison.Equals(local.Name, localForFunctionValue.Name) Then
' Does name conflict with the function name?
ReportDiagnostic(diagnostics, nameSyntax, ERRID.ERR_LocalSameAsFunc)
Else
Dim result = LookupResult.GetInstance()
Lookup(result, identifier.ValueText, 0, Nothing, useSiteDiagnostics:=Nothing)
' A local symbol will always be found because all local declarations are put into the
' local map in the blockbasebinder.
Debug.Assert(result.HasSingleSymbol AndAlso result.IsGood)
Dim lookupSymbol = DirectCast(result.SingleSymbol, LocalSymbol)
result.Free()
If lookupSymbol.IdentifierToken.FullSpan <> identifier.FullSpan Then
If lookupSymbol.CanBeReferencedByName Then
' Static Locals have there own diagnostic. ERR_DuplicateLocalStatic1
If Not lookupSymbol.IsStatic OrElse Not local.IsStatic Then
' If location does not match then this is a duplicate local, unless it has an invalid name (the syntax was bad)
ReportDiagnostic(diagnostics, nameSyntax, ERRID.ERR_DuplicateLocals1, name)
' Difference to Dev10:
' For r as Integer in New Integer() {}
' Dim r as Integer = 23
' next
' Does not give a BC30288 "Local variable 'r' is already declared in the current block.", but a
' BC30616 "Variable 'r' hides a variable in an enclosing block." with the same location.
' The reason is the binder hierarchy, where the ForOrForEachBlockBinder and the StatementListBinder both have
' r in their locals set. When looking up the symbol one gets the inner symbol and then the FullSpans match
' which then does not trigger the condition above.
End If
End If
Else
' Look up in container binders for name clashes with other locals, parameters and type parameters.
' Stop at the named type binder
Dim container = Me.ContainingBinder
If container IsNot Nothing Then
container.VerifyNameShadowingInMethodBody(local, nameSyntax, identifier, diagnostics)
End If
End If
End If
End Sub
''' <summary>
''' Should be called on the binder, at which the check should begin.
''' </summary>
Private Sub VerifyNameShadowingInMethodBody(
symbol As Symbol,
nameSyntax As SyntaxNodeOrToken,
identifier As SyntaxNodeOrToken,
diagnostics As DiagnosticBag
)
Debug.Assert(symbol.Kind = SymbolKind.Local OrElse symbol.Kind = SymbolKind.RangeVariable OrElse
(symbol.Kind = SymbolKind.Parameter AndAlso
TypeOf symbol Is UnboundLambdaParameterSymbol))
Dim name As String = symbol.Name
' Look up in container binders for name clashes with other locals, parameters and type parameters.
' Stop at the named type binder
Dim container = Me
Dim result = LookupResult.GetInstance
Dim err As ERRID
Do
Dim namedTypeBinder = TryCast(container, namedTypeBinder)
If namedTypeBinder IsNot Nothing Then
Exit Do
End If
result.Clear()
container.LookupInSingleBinder(result, name, 0, Nothing, Me, useSiteDiagnostics:=Nothing)
If result.HasSingleSymbol Then
Dim altSymbol = result.SingleSymbol
If altSymbol IsNot symbol Then
Select Case altSymbol.Kind
Case SymbolKind.Local, SymbolKind.RangeVariable
If symbol.Kind = SymbolKind.Parameter Then
err = ERRID.ERR_LambdaParamShadowLocal1
ElseIf symbol.Kind <> SymbolKind.RangeVariable Then
err = ERRID.ERR_BlockLocalShadowing1
ElseIf Me.ImplicitVariableDeclarationAllowed Then
err = ERRID.ERR_IterationVariableShadowLocal2
Else
err = ERRID.ERR_IterationVariableShadowLocal1
End If
ReportDiagnostic(diagnostics, nameSyntax, err, name)
Case SymbolKind.Parameter
If symbol.Kind = SymbolKind.Parameter Then
err = ERRID.ERR_LambdaParamShadowLocal1
ElseIf symbol.Kind <> SymbolKind.RangeVariable Then
If DirectCast(altSymbol.ContainingSymbol, MethodSymbol).MethodKind = MethodKind.LambdaMethod Then
err = ERRID.ERR_LocalNamedSameAsParamInLambda1
Else
err = ERRID.ERR_LocalNamedSameAsParam1
End If
ElseIf Me.ImplicitVariableDeclarationAllowed Then
err = ERRID.ERR_IterationVariableShadowLocal2
Else
err = ERRID.ERR_IterationVariableShadowLocal1
' Change from Dev10: we're now also correctly reporting this error for control variables
' of for/for each loops when they shadow variables that are parameters.
End If
ReportDiagnostic(diagnostics, nameSyntax, err, name)
Case SymbolKind.TypeParameter
' this diagnostic will not be shown if the symbol is for or for each local has an inferred type
Dim local = TryCast(symbol, LocalSymbol)
If local Is Nothing OrElse
Not (local.IsFor OrElse local.IsForEach) OrElse
Not local.HasInferredType Then
ReportDiagnostic(diagnostics, nameSyntax, ERRID.ERR_NameSameAsMethodTypeParam1, name)
End If
End Select
End If
Exit Do
End If
Dim implicitVariableBinder = TryCast(container, implicitVariableBinder)
If implicitVariableBinder IsNot Nothing AndAlso Not implicitVariableBinder.AllImplicitVariableDeclarationsAreHandled Then
' If an implicit local comes into being later, then report an error here.
If symbol.Kind = SymbolKind.Parameter Then
err = ERRID.ERR_LambdaParamShadowLocal1
ElseIf symbol.Kind <> SymbolKind.RangeVariable Then
err = ERRID.ERR_BlockLocalShadowing1
Else
err = ERRID.ERR_IterationVariableShadowLocal2
End If
implicitVariableBinder.RememberPossibleShadowingVariable(name, identifier, err)
End If
container = container.ContainingBinder
Loop While container IsNot Nothing
result.Free()
End Sub
Friend Function AdjustAssignmentTarget(node As SyntaxNode, op1 As BoundExpression, diagnostics As DiagnosticBag, ByRef isError As Boolean) As BoundExpression
Select Case op1.Kind
Case BoundKind.XmlMemberAccess
Dim memberAccess = DirectCast(op1, BoundXmlMemberAccess)
Dim expr = AdjustAssignmentTarget(node, memberAccess.MemberAccess, diagnostics, isError)
Return memberAccess.Update(expr)
Case BoundKind.PropertyAccess
Dim propertyAccess As BoundPropertyAccess = DirectCast(op1, BoundPropertyAccess)
Dim propertySymbol As PropertySymbol = propertyAccess.PropertySymbol
If propertyAccess.IsLValue Then
Debug.Assert(propertySymbol.ReturnsByRef)
WarnOnRecursiveAccess(propertyAccess, PropertyAccessKind.Get, diagnostics)
Return propertyAccess.SetAccessKind(PropertyAccessKind.Get)
End If
Debug.Assert(propertyAccess.AccessKind <> PropertyAccessKind.Get)
If Not propertyAccess.IsWriteable Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_NoSetProperty1, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol))
isError = True
Else
Dim setMethod = propertySymbol.GetMostDerivedSetMethod()
' NOTE: the setMethod could not be present, while it would still be
' possible to write to the property in a case
' where the property is a getter-only autoproperty
' and the writing is happening in the corresponding constructor or initializer
If setMethod IsNot Nothing Then
ReportDiagnosticsIfObsolete(diagnostics, setMethod, node)
If ReportUseSiteError(diagnostics, op1.Syntax, setMethod) Then
isError = True
Else
Dim accessThroughType = GetAccessThroughType(propertyAccess.ReceiverOpt)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not IsAccessible(setMethod, useSiteDiagnostics, accessThroughType) AndAlso
IsAccessible(propertySymbol, useSiteDiagnostics, accessThroughType) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_NoAccessibleSet, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol))
isError = True
End If
diagnostics.Add(node, useSiteDiagnostics)
End If
End If
End If
WarnOnRecursiveAccess(propertyAccess, PropertyAccessKind.Set, diagnostics)
Return propertyAccess.SetAccessKind(PropertyAccessKind.Set)
Case BoundKind.LateMemberAccess
Debug.Assert((DirectCast(op1, BoundLateMemberAccess).AccessKind And (LateBoundAccessKind.Get Or LateBoundAccessKind.Call)) = 0)
Return DirectCast(op1, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Set)
Case BoundKind.LateInvocation
Debug.Assert((DirectCast(op1, BoundLateInvocation).AccessKind And (LateBoundAccessKind.Get Or LateBoundAccessKind.Call)) = 0)
Return DirectCast(op1, BoundLateInvocation).SetAccessKind(LateBoundAccessKind.Set)
Case Else
Return op1
End Select
End Function
Private Function BindAssignment(node As SyntaxNode, op1 As BoundExpression, op2 As BoundExpression, diagnostics As DiagnosticBag) As BoundAssignmentOperator
Dim isError As Boolean = False
op1 = AdjustAssignmentTarget(node, op1, diagnostics, isError)
Dim targetType As TypeSymbol = op1.Type
Debug.Assert(targetType IsNot Nothing OrElse isError)
If targetType IsNot Nothing Then
op2 = ApplyImplicitConversion(op2.Syntax, targetType, op2, diagnostics)
Else
' Try to reclassify op2 if we still can.
op2 = MakeRValueAndIgnoreDiagnostics(op2)
End If
Return New BoundAssignmentOperator(node, op1, op2, False, hasErrors:=isError)
End Function
Private Function BindCompoundAssignment(
node As VisualBasicSyntaxNode,
left As BoundExpression,
right As BoundExpression,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
diagnostics As DiagnosticBag
) As BoundAssignmentOperator
Dim isError As Boolean = False
' We should be able to use the 'left' as an assignment target and as an RValue.
' Let's verify that
Dim assignmentTarget As BoundExpression = AdjustAssignmentTarget(node, left, diagnostics, isError)
Dim rValue As BoundExpression
If isError Then
rValue = MakeRValueAndIgnoreDiagnostics(left)
Else
rValue = MakeRValue(left, diagnostics)
isError = rValue.HasErrors
End If
Dim targetType As TypeSymbol = assignmentTarget.Type
Debug.Assert(targetType IsNot Nothing OrElse isError)
Dim placeholder As BoundCompoundAssignmentTargetPlaceholder = Nothing
If Not isError Then
placeholder = New BoundCompoundAssignmentTargetPlaceholder(left.Syntax, targetType).MakeCompilerGenerated()
right = BindBinaryOperator(node, placeholder, right, operatorTokenKind, operatorKind, isOperandOfConditionalBranch:=False, diagnostics:=diagnostics)
right.SetWasCompilerGenerated()
right = ApplyImplicitConversion(node, targetType, right, diagnostics)
Else
' Try to reclassify 'right' if we still can.
right = MakeRValueAndIgnoreDiagnostics(right)
End If
left = left.SetGetSetAccessKindIfAppropriate()
Return New BoundAssignmentOperator(node, left, placeholder, right, False, hasErrors:=isError)
End Function
''' <summary>
''' Binds a list of statements and puts in a scope.
''' </summary>
Friend Function BindBlock(syntax As SyntaxNode, stmtList As SyntaxList(Of StatementSyntax), diagnostics As DiagnosticBag) As BoundBlock
Dim stmtListBinder = Me.GetBinder(stmtList)
Return BindBlock(syntax, stmtList, diagnostics, stmtListBinder)
End Function
''' <summary>
''' Binds a list of statements and puts in a scope.
''' </summary>
Friend Function BindBlock(syntax As SyntaxNode, stmtList As SyntaxList(Of StatementSyntax), diagnostics As DiagnosticBag, stmtListBinder As Binder) As BoundBlock
Dim boundStatements(stmtList.Count - 1) As BoundStatement
Dim locals As ArrayBuilder(Of LocalSymbol) = Nothing
For i = 0 To boundStatements.Length - 1
Dim boundStatement As BoundStatement = stmtListBinder.BindStatement(stmtList(i), diagnostics)
boundStatements(i) = boundStatement
Select Case boundStatement.Kind
Case BoundKind.LocalDeclaration
Dim localDecl As BoundLocalDeclaration = DirectCast(boundStatement, BoundLocalDeclaration)
DeclareLocal(locals, localDecl)
Case BoundKind.AsNewLocalDeclarations
Dim asNewLocalDecls As BoundAsNewLocalDeclarations = DirectCast(boundStatement, BoundAsNewLocalDeclarations)
DeclareLocal(locals, asNewLocalDecls)
Case BoundKind.DimStatement
Dim multipleDecl As BoundDimStatement = DirectCast(boundStatement, BoundDimStatement)
For Each localDecl In multipleDecl.LocalDeclarations
DeclareLocal(locals, localDecl)
Next
End Select
Next i
If locals Is Nothing Then
Return New BoundBlock(syntax, stmtList, ImmutableArray(Of LocalSymbol).Empty, boundStatements.AsImmutableOrNull())
End If
Return New BoundBlock(syntax, stmtList, locals.ToImmutableAndFree, boundStatements.AsImmutableOrNull())
End Function
Private Shared Sub DeclareLocal(ByRef locals As ArrayBuilder(Of LocalSymbol), localDecl As BoundLocalDeclarationBase)
If locals Is Nothing Then
locals = ArrayBuilder(Of LocalSymbol).GetInstance
End If
Select Case localDecl.Kind
Case BoundKind.LocalDeclaration
locals.Add(DirectCast(localDecl, BoundLocalDeclaration).LocalSymbol)
Case BoundKind.AsNewLocalDeclarations
For Each decl In DirectCast(localDecl, BoundAsNewLocalDeclarations).LocalDeclarations
locals.Add(DirectCast(decl, BoundLocalDeclaration).LocalSymbol)
Next
Case Else
Throw ExceptionUtilities.UnexpectedValue(localDecl.Kind)
End Select
End Sub
Private Function BindAssignmentStatement(node As AssignmentStatementSyntax, diagnostics As DiagnosticBag) As BoundExpressionStatement
Debug.Assert(node IsNot Nothing)
Dim op1 As BoundExpression = Me.BindAssignmentTarget(node.Left, diagnostics)
Dim op2 As BoundExpression = Me.BindValue(node.Right, diagnostics)
Debug.Assert(op1 IsNot Nothing)
Debug.Assert(op2 IsNot Nothing)
Dim expr As BoundAssignmentOperator
If (op1.HasErrors OrElse op2.HasErrors) Then
If Not op1.HasErrors AndAlso node.Kind = SyntaxKind.SimpleAssignmentStatement Then
expr = New BoundAssignmentOperator(node, op1,
ApplyImplicitConversion(node.Right, op1.Type, op2, diagnostics, False),
False,
op1.Type,
hasErrors:=True)
Else
' Try to reclassify op2 if we still can.
op2 = MakeRValueAndIgnoreDiagnostics(op2)
expr = New BoundAssignmentOperator(node, op1, op2, False, op1.Type, hasErrors:=True)
End If
ElseIf node.Kind = SyntaxKind.SimpleAssignmentStatement Then
expr = BindAssignment(node, op1, op2, diagnostics)
Else
Dim operatorKind As BinaryOperatorKind
Dim binaryTokenKind As SyntaxKind
Select Case node.Kind
Case SyntaxKind.AddAssignmentStatement
operatorKind = BinaryOperatorKind.Add
binaryTokenKind = SyntaxKind.PlusToken
Case SyntaxKind.SubtractAssignmentStatement
operatorKind = BinaryOperatorKind.Subtract
binaryTokenKind = SyntaxKind.MinusToken
Case SyntaxKind.MultiplyAssignmentStatement
operatorKind = BinaryOperatorKind.Multiply
binaryTokenKind = SyntaxKind.AsteriskToken
Case SyntaxKind.DivideAssignmentStatement
operatorKind = BinaryOperatorKind.Divide
binaryTokenKind = SyntaxKind.SlashToken
Case SyntaxKind.IntegerDivideAssignmentStatement
operatorKind = BinaryOperatorKind.IntegerDivide
binaryTokenKind = SyntaxKind.BackslashToken
Case SyntaxKind.ExponentiateAssignmentStatement
operatorKind = BinaryOperatorKind.Power
binaryTokenKind = SyntaxKind.CaretToken
Case SyntaxKind.LeftShiftAssignmentStatement
operatorKind = BinaryOperatorKind.LeftShift
binaryTokenKind = SyntaxKind.LessThanLessThanToken
Case SyntaxKind.RightShiftAssignmentStatement
operatorKind = BinaryOperatorKind.RightShift
binaryTokenKind = SyntaxKind.GreaterThanGreaterThanToken
Case SyntaxKind.ConcatenateAssignmentStatement
operatorKind = BinaryOperatorKind.Concatenate
binaryTokenKind = SyntaxKind.AmpersandToken
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
expr = BindCompoundAssignment(node, op1, op2, binaryTokenKind, operatorKind, diagnostics)
End If
Return New BoundExpressionStatement(node, expr)
End Function
Private Function BindMidAssignmentStatement(node As AssignmentStatementSyntax, diagnostics As DiagnosticBag) As BoundExpressionStatement
Debug.Assert(node IsNot Nothing AndAlso node.Kind = SyntaxKind.MidAssignmentStatement AndAlso node.Left.Kind = SyntaxKind.MidExpression)
Dim midExpression = DirectCast(node.Left, MidExpressionSyntax)
Dim midArguments As SeparatedSyntaxList(Of ArgumentSyntax) = midExpression.ArgumentList.Arguments
Debug.Assert(midArguments.Count = 2 OrElse midArguments.Count = 3)
Dim targetSyntax = DirectCast(midArguments(0), SimpleArgumentSyntax).Expression
Dim target As BoundExpression = BindAssignmentTarget(targetSyntax, diagnostics)
Dim int32 As NamedTypeSymbol = GetSpecialType(SpecialType.System_Int32, midExpression, diagnostics)
Dim startSyntax = DirectCast(midArguments(1), SimpleArgumentSyntax).Expression
Dim start As BoundExpression = ApplyImplicitConversion(startSyntax, int32, BindValue(startSyntax, diagnostics), diagnostics)
Dim lengthOpt As BoundExpression = Nothing
If midArguments.Count > 2 Then
Dim lengthSyntax = DirectCast(midArguments(2), SimpleArgumentSyntax).Expression
lengthOpt = ApplyImplicitConversion(lengthSyntax, int32, BindValue(lengthSyntax, diagnostics), diagnostics)
End If
Dim stringType As NamedTypeSymbol = GetSpecialType(SpecialType.System_String, midExpression, diagnostics)
VerifyTypeCharacterConsistency(midExpression.Mid, stringType, midExpression.Mid.GetTypeCharacter(), diagnostics)
Dim source As BoundExpression = ApplyImplicitConversion(node.Right, stringType, BindValue(node.Right, diagnostics), diagnostics)
' We should be able to use the 'target' as an assignment target and as an RValue.
' Let's verify that
Dim isError As Boolean
Dim assignmentTarget As BoundExpression = AdjustAssignmentTarget(targetSyntax, target, diagnostics, isError)
If Not isError Then
isError = MakeRValue(target, diagnostics).HasErrors
End If
Dim targetType As TypeSymbol = assignmentTarget.Type
Debug.Assert(targetType IsNot Nothing OrElse isError)
Dim placeholder As BoundCompoundAssignmentTargetPlaceholder
Dim original As BoundExpression
If Not isError Then
placeholder = New BoundCompoundAssignmentTargetPlaceholder(targetSyntax, targetType).MakeCompilerGenerated()
original = ApplyImplicitConversion(targetSyntax, stringType, placeholder, diagnostics)
Else
placeholder = Nothing
original = BadExpression(targetSyntax, stringType).MakeCompilerGenerated()
End If
' SemanticModel should be able to find node corresponding to the MidExpressionSyntax, which has type String and no associated symbols.
' Wrapping 'original' with BoundParenthesized node tied to MidExpressionSyntax should suffice for this purpose.
Dim right As BoundExpression = New BoundMidResult(node,
New BoundParenthesized(midExpression, original, original.Type),
start, lengthOpt, source, stringType).MakeCompilerGenerated()
If Not isError Then
right = ApplyImplicitConversion(node, targetType, right, diagnostics).MakeCompilerGenerated()
' Either we have both "in" and "out" conversions or none.
Debug.Assert((original.Kind = BoundKind.CompoundAssignmentTargetPlaceholder) = (right.Kind = BoundKind.MidResult) OrElse original.HasErrors OrElse right.HasErrors)
End If
target = target.SetGetSetAccessKindIfAppropriate()
Return New BoundExpressionStatement(node, New BoundAssignmentOperator(node, target, placeholder, right, False,
Compilation.GetSpecialType(SpecialType.System_Void),
hasErrors:=isError))
End Function
Private Function BindAddRemoveHandlerStatement(node As AddRemoveHandlerStatementSyntax, diagnostics As DiagnosticBag) As BoundAddRemoveHandlerStatement
Dim eventSymbol As eventSymbol = Nothing
Dim actualEventAccess As BoundEventAccess = Nothing
Dim eventAccess As BoundExpression = BindEventAccess(node.EventExpression, diagnostics, actualEventAccess, eventSymbol)
Dim handlerExpression = BindValue(node.DelegateExpression, diagnostics)
Dim isRemoveHandler As Boolean = node.Kind = SyntaxKind.RemoveHandlerStatement
If isRemoveHandler Then
Dim toCheck As BoundExpression = handlerExpression
' Dig through parenthesized.
toCheck = toCheck.GetMostEnclosedParenthesizedExpression()
If toCheck.Kind = BoundKind.UnboundLambda Then
ReportDiagnostic(diagnostics, node.DelegateExpression, ERRID.WRN_LambdaPassedToRemoveHandler)
End If
End If
' we may need to convert handler to the accessor parameter type.
' in a case where handler is a lambda or AddressOf we definitely need a conversion
' NOTE that handler may not be a delegate, but could have a user defined conversion to a delegate.
Dim hasErrors As Boolean = True
If eventSymbol IsNot Nothing Then
Dim method = If(node.Kind = SyntaxKind.AddHandlerStatement, eventSymbol.AddMethod, eventSymbol.RemoveMethod)
If method Is Nothing Then
If eventSymbol.DeclaringCompilation IsNot Me.Compilation Then
ReportDiagnostic(diagnostics, node.EventExpression, ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedEvent1, eventSymbol))
End If
Else
Dim targetType = eventSymbol.Type
handlerExpression = ApplyImplicitConversion(node.DelegateExpression, targetType, handlerExpression, diagnostics)
If isRemoveHandler AndAlso
handlerExpression.Kind = BoundKind.DelegateCreationExpression AndAlso
node.DelegateExpression.Kind = SyntaxKind.AddressOfExpression Then
Dim delCreation = DirectCast(handlerExpression, BoundDelegateCreationExpression)
If delCreation.RelaxationLambdaOpt IsNot Nothing Then
Dim addrOffExpr = DirectCast(node.DelegateExpression, UnaryExpressionSyntax)
ReportDiagnostic(diagnostics, addrOffExpr.Operand, ERRID.WRN_RelDelegatePassedToRemoveHandler)
End If
End If
hasErrors = False
If method = Me.ContainingMember Then
If method.IsShared OrElse actualEventAccess.ReceiverOpt.IsMeReference Then
'Statement recursively calls the containing '{0}' for event '{1}'.
ReportDiagnostic(diagnostics,
node,
ERRID.WRN_RecursiveAddHandlerCall,
node.AddHandlerOrRemoveHandlerKeyword.ToString,
eventSymbol.Name)
End If
End If
If Not targetType.IsDelegateType() Then
If eventSymbol.DeclaringCompilation IsNot Me.Compilation AndAlso TypeOf targetType IsNot MissingMetadataTypeSymbol Then
ReportDiagnostic(diagnostics, node.EventExpression, ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedEvent1, eventSymbol))
End If
hasErrors = True
Else
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim accessThroughType = GetAccessThroughType(actualEventAccess.ReceiverOpt)
If Not Me.IsAccessible(method, useSiteDiagnostics, accessThroughType) Then
Debug.Assert(eventSymbol.DeclaringCompilation IsNot Me.Compilation)
ReportDiagnostic(diagnostics, node.EventExpression, GetInaccessibleErrorInfo(method))
End If
diagnostics.Add(node.EventExpression, useSiteDiagnostics)
Dim badShape As Boolean = False
Dim useSiteError As DiagnosticInfo = Nothing
' Decrease noise in diagnostics, if event is "bad", we already complained about it.
If eventSymbol.GetUseSiteErrorInfo() Is Nothing Then
useSiteError = method.GetUseSiteErrorInfo()
End If
If useSiteError IsNot Nothing Then
Debug.Assert(eventSymbol.DeclaringCompilation IsNot Me.Compilation)
ReportDiagnostic(diagnostics, node.EventExpression, useSiteError)
hasErrors = True
ElseIf method.ParameterCount <> 1 OrElse method.Parameters(0).IsByRef Then
badShape = True
ElseIf eventSymbol.IsWindowsRuntimeEvent Then
Dim tokenType As NamedTypeSymbol = Me.Compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
If node.Kind = SyntaxKind.AddHandlerStatement Then
If Not method.Parameters(0).Type.IsSameTypeIgnoringAll(targetType) OrElse
Not method.ReturnType.IsSameTypeIgnoringAll(tokenType) Then
badShape = True
End If
ElseIf Not method.Parameters(0).Type.IsSameTypeIgnoringAll(tokenType) OrElse Not method.IsSub Then
badShape = True
End If
ElseIf Not method.Parameters(0).Type.IsSameTypeIgnoringAll(targetType) Then
badShape = True
End If
If badShape Then
If eventSymbol.DeclaringCompilation IsNot Me.Compilation Then
ReportDiagnostic(diagnostics, node.EventExpression, ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, method))
End If
hasErrors = True
End If
End If
End If
End If
If node.Kind = SyntaxKind.AddHandlerStatement Then
Return New BoundAddHandlerStatement(node, eventAccess, handlerExpression, hasErrors:=hasErrors)
Else
Return New BoundRemoveHandlerStatement(node, eventAccess, handlerExpression, hasErrors:=hasErrors)
End If
End Function
Private Function BindEventAccess(node As ExpressionSyntax,
diagnostics As DiagnosticBag,
<Out()> ByRef actualEventAccess As BoundEventAccess,
<Out()> ByRef eventSymbol As EventSymbol) As BoundExpression
' event must be a simple name that could be qualified and perhaps parenthesized
' Examples: goo , (goo) , (bar.goo) , baz.moo(of T).goo
Dim notParenthesizedSyntax = node
While notParenthesizedSyntax.Kind = SyntaxKind.ParenthesizedExpression
notParenthesizedSyntax = DirectCast(notParenthesizedSyntax, ParenthesizedExpressionSyntax).Expression
End While
Dim notQualifiedSyntax = notParenthesizedSyntax
If notQualifiedSyntax.Kind = SyntaxKind.SimpleMemberAccessExpression Then
notQualifiedSyntax = DirectCast(notQualifiedSyntax, MemberAccessExpressionSyntax).Name
End If
If notQualifiedSyntax.Kind <> SyntaxKind.IdentifierName Then
ReportDiagnostic(diagnostics, notQualifiedSyntax, ERRID.ERR_AddOrRemoveHandlerEvent)
Dim ignoreDiagnostics = DiagnosticBag.GetInstance()
Dim errorRecovery As BoundExpression = BindRValue(node, ignoreDiagnostics)
ignoreDiagnostics.Free()
Return errorRecovery
End If
'NOTE this may bind to extension methods.
'It could be unnecessary perf hit, but it will happen only in error cases (event not found)
'so is not a big concern.
Dim result As BoundExpression
' when binding a simple name event we know that it must be a member since methods do not declare events
If notParenthesizedSyntax.Kind = SyntaxKind.IdentifierName Then
Dim simpleNameSyntax As simpleNameSyntax = DirectCast(notParenthesizedSyntax, IdentifierNameSyntax)
result = BindSimpleName(simpleNameSyntax, False, diagnostics, skipLocalsAndParameters:=True)
Else
result = BindExpression(node, isInvocationOrAddressOf:=False, isOperandOfConditionalBranch:=False, eventContext:=True, diagnostics:=diagnostics)
End If
Debug.Assert(result IsNot Nothing)
' Dev10 allows parenthesizing of the event
Dim notParenthesized = result.GetMostEnclosedParenthesizedExpression()
If notParenthesized.Kind = BoundKind.EventAccess Then
actualEventAccess = DirectCast(notParenthesized, BoundEventAccess)
eventSymbol = actualEventAccess.EventSymbol
Else
' TODO: Should try to report ERR_NameNotEvent2 without making notParenthesized an RValue,
' it might cause errors for write-only property, etc.
notParenthesized = MakeRValue(notParenthesized, diagnostics)
' this is not an event. Add diagnostics if node is not already bad
' NOTE that we are not marking the node as bad if it is not
' in such case there is nothing wrong with the event access node.
' However since we cannot provide event symbol, the AddRemovehandler
' node will be marked as HasErrors.
If Not notParenthesized.HasErrors Then
Dim name = DirectCast(notQualifiedSyntax, IdentifierNameSyntax).Identifier.ValueText
Dim exprSymbol = notParenthesized.ExpressionSymbol
Dim container = If(exprSymbol IsNot Nothing, exprSymbol.ContainingSymbol, Compilation.GetSpecialType(SpecialType.System_Object))
ReportDiagnostic(diagnostics, notQualifiedSyntax, ERRID.ERR_NameNotEvent2, name, container)
End If
End If
Return result
End Function
Private Function BindRaiseEventStatement(node As RaiseEventStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim hasErrors = False
Dim target As BoundExpression = BindSimpleName(node.Name, False, diagnostics, skipLocalsAndParameters:=True)
If target.Kind <> BoundKind.EventAccess Then
If Not target.HasErrors Then
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_NameNotEvent2, node.Name.ToString, Me.ContainingType)
End If
Return New BoundBadStatement(node, ImmutableArray.Create(Of BoundNode)(target), True)
End If
Dim targetAsEvent = DirectCast(target, BoundEventAccess)
' Get the bound arguments and the argument names.
Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing
Dim argumentNames As ImmutableArray(Of String) = Nothing
Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing
BindArgumentsAndNames(node.ArgumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics)
Dim eventSym = targetAsEvent.EventSymbol
Dim receiver As BoundExpression
Dim fireMethod As MethodSymbol
If eventSym.HasAssociatedField Then
' field is not nothing when event IsFieldLike
Dim eventField = eventSym.AssociatedField
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not IsAccessible(eventField, useSiteDiagnostics, Me.ContainingType) Then
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_CantRaiseBaseEvent)
hasErrors = True
End If
diagnostics.Add(node.Name, useSiteDiagnostics)
Debug.Assert(targetAsEvent.Type = eventField.Type OrElse eventSym.IsWindowsRuntimeEvent, "non-WinRT event should have the same type as its backing field")
receiver = New BoundFieldAccess(node.Name,
targetAsEvent.ReceiverOpt,
eventField,
False,
eventField.Type).MakeCompilerGenerated
Dim eventType = TryCast(eventSym.Type, NamedTypeSymbol)
' Detect circumstances where we can't continue.
If eventType Is Nothing OrElse eventType.DelegateInvokeMethod Is Nothing Then
' If we have a delegate type and it has no Invoke method, then we should give a diagnostic.
' Dev10 gives no diagnostics here, but we should.
' If something else went wrong (i.e. we don't have a delegate type), then a diagnostic was reported elsewhere.
If eventType IsNot Nothing AndAlso eventType.IsDelegateType Then
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_EventTypeNotDelegate)
End If
Return New BoundBadStatement(node, StaticCast(Of BoundNode).From(boundArguments).Add(target), True)
End If
fireMethod = eventType.DelegateInvokeMethod
If ReportUseSiteError(diagnostics, node.Name, fireMethod) Then
hasErrors = True
End If
If Not fireMethod.IsSub Then
' // Something is bad somewhere.
' Dev10 gives no diagnostics here, but we should.
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_EventsCantBeFunctions)
Return New BoundBadStatement(node, StaticCast(Of BoundNode).From(boundArguments).Add(target), True)
End If
Else
receiver = targetAsEvent.ReceiverOpt
fireMethod = eventSym.RaiseMethod
If fireMethod Is Nothing Then
' // Something is bad somewhere.
' Dev10 gives no diagnostics here, but we should.
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_MissingRaiseEventDef1, node.Name.ToString)
Return New BoundBadStatement(node, StaticCast(Of BoundNode).From(boundArguments).Add(target), True)
End If
If ReportUseSiteError(diagnostics, node.Name, fireMethod) Then
hasErrors = True
End If
If Not fireMethod.IsSub Then
' // Something is bad somewhere.
' Dev10 gives no diagnostics here, but we should.
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_EventsCantBeFunctions)
Return New BoundBadStatement(node, StaticCast(Of BoundNode).From(boundArguments).Add(target), True)
End If
If fireMethod.ContainingType <> Me.ContainingType Then
' Re: Dev10
' // UNDONE: harishk - note that this is different from the check for an
' // accessible event field for non-block events. This is because there
' // is a bug for non-block events which contrary to the spec does allow
' // base class events to be raised in some scenarios. Sent email to
' // paulv and amandas to check if we can update all of this according
' // to spec. After a final answer is received, we will need to make
' // both consistent. More work is required if we need to make block
' // events' behavior be the same as that of non-block events. Also for
' // both cases, it would be hard to get the raising of base events
' // working for metadata events.
'
' 'RaiseEvent' definition missing for event '{0}'.
ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_CantRaiseBaseEvent, node.Name.ToString)
Return New BoundBadStatement(node, StaticCast(Of BoundNode).From(boundArguments).Add(target), True)
End If
End If
Debug.Assert(fireMethod.IsSub, "we got this far, we must have a valid fireMethod")
If fireMethod = Me.ContainingMember Then
If fireMethod.IsShared OrElse receiver.IsMeReference Then
'Statement recursively calls the containing '{0}' for event '{1}'.
ReportDiagnostic(diagnostics,
node,
ERRID.WRN_RecursiveAddHandlerCall,
node.RaiseEventKeyword.ToString,
eventSym.Name)
End If
End If
' eventDelegateField.Invoke
Dim methodGroup = New BoundMethodGroup(node,
Nothing,
ImmutableArray.Create(fireMethod),
LookupResultKind.Good,
receiver,
QualificationKind.QualifiedViaValue)
'NOTE: Dev10 allows and ignores type characters on the event here.
Dim invocation = BindInvocationExpression(node,
node.Name,
TypeCharacter.None,
methodGroup,
boundArguments,
argumentNames,
diagnostics,
callerInfoOpt:=Nothing,
representCandidateInDiagnosticsOpt:=eventSym).MakeCompilerGenerated
Return New BoundRaiseEventStatement(node, eventSym, invocation, hasErrors)
End Function
Private Function BindExpressionStatement(statement As ExpressionStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim expression = statement.Expression
Dim boundExpression As boundExpression
Select Case expression.Kind
Case SyntaxKind.InvocationExpression,
SyntaxKind.ConditionalAccessExpression
boundExpression = BindInvocationExpressionAsStatement(expression, diagnostics)
Case SyntaxKind.AwaitExpression
boundExpression = BindAwait(DirectCast(expression, AwaitExpressionSyntax), diagnostics, bindAsStatement:=True)
Case Else
' TODO(ADGreen): This case covers top-level expressions in interactive.
' Otherwise it should be an error.
boundExpression = BindRValue(expression, diagnostics)
End Select
WarnOnUnobservedCallThatReturnsAnAwaitable(statement, boundExpression, diagnostics)
Return New BoundExpressionStatement(statement, boundExpression)
End Function
Private Sub WarnOnUnobservedCallThatReturnsAnAwaitable(statement As ExpressionStatementSyntax, boundExpression As BoundExpression, diagnostics As DiagnosticBag)
If boundExpression.Kind = BoundKind.ConditionalAccess Then
WarnOnUnobservedCallThatReturnsAnAwaitable(statement, DirectCast(boundExpression, BoundConditionalAccess).AccessExpression, diagnostics)
Return
End If
If Not boundExpression.HasErrors AndAlso
Not boundExpression.Kind = BoundKind.AwaitOperator AndAlso
Not boundExpression.Type.IsErrorType() AndAlso
Not boundExpression.Type.IsVoidType() AndAlso
Not boundExpression.Type.IsObjectType() Then
' Check if we should warn for an unobserved call that returns an awaitable value.
' We will show a warning:
' 1. In any method, when invoking a method that is marked
' "Async" and returns a type other than void. Note that
' this requires the caller and callee to be in the same
' compilation unit, as "Async" is not propagated into
' metadata.
' 2. In any method, when invoking a method that returns one
' of the Windows Runtime async types:
' IAsyncAction
' IAsyncActionWithProgress(Of T)
' IAsyncOperation(Of T)
' IAsyncOperationWithProgress(Of T, U)
' 3. In an async method, when invoking a method that returns
' any awaitable type.
Dim warn As Boolean = False
If boundExpression.Kind = BoundKind.Call Then
Dim [call] = DirectCast(boundExpression, BoundCall)
' 1.
warn = [call].Method.IsAsync AndAlso [call].Method.ContainingAssembly Is Me.Compilation.Assembly
End If
If Not warn Then
' 2.
If IsOrInheritsFromOrImplementsInterface(boundExpression.Type, WellKnownType.Windows_Foundation_IAsyncAction, useSiteDiagnostics:=Nothing) OrElse
IsOrInheritsFromOrImplementsInterface(boundExpression.Type, WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T, useSiteDiagnostics:=Nothing) OrElse
IsOrInheritsFromOrImplementsInterface(boundExpression.Type, WellKnownType.Windows_Foundation_IAsyncOperation_T, useSiteDiagnostics:=Nothing) OrElse
IsOrInheritsFromOrImplementsInterface(boundExpression.Type, WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2, useSiteDiagnostics:=Nothing) Then
warn = True
ElseIf IsInAsyncContext() Then
' 3.
Dim diagBag = DiagnosticBag.GetInstance()
If Not BindAwait(statement, boundExpression, diagBag, bindAsStatement:=True).HasErrors AndAlso Not diagBag.HasAnyErrors Then
warn = True
End If
diagBag.Free()
End If
End If
If warn Then
ReportDiagnostic(diagnostics, statement, ERRID.WRN_UnobservedAwaitableExpression)
End If
End If
End Sub
Private Function IsOrInheritsFromOrImplementsInterface(derivedType As TypeSymbol, interfaceType As WellKnownType, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Dim type As NamedTypeSymbol = Compilation.GetWellKnownType(interfaceType)
Return Not type.IsErrorType() AndAlso type.IsInterfaceType() AndAlso
IsOrInheritsFromOrImplementsInterface(derivedType, type, useSiteDiagnostics)
End Function
Private Function BindPrintStatement(printStmt As PrintStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim boundExpression As boundExpression = BindRValue(printStmt.Expression, diagnostics)
Return New BoundExpressionStatement(printStmt, boundExpression)
End Function
Private Function BindCallStatement(callStmt As CallStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim boundInvocation As BoundExpression = BindInvocationExpressionAsStatement(callStmt.Invocation, diagnostics)
Return New BoundExpressionStatement(callStmt, boundInvocation)
End Function
Private Function BindInvocationExpressionAsStatement(expression As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
Return ReclassifyInvocationExpressionAsStatement(BindExpression(expression, diagnostics), diagnostics)
End Function
Friend Function ReclassifyInvocationExpressionAsStatement(boundInvocation As BoundExpression, diagnostics As DiagnosticBag) As BoundExpression
Select Case boundInvocation.Kind
Case BoundKind.PropertyAccess
boundInvocation = MakeRValue(boundInvocation, diagnostics)
' specially for properties being called in Call statement context
If Not boundInvocation.HasErrors Then
ReportDiagnostic(diagnostics, boundInvocation.Syntax, ERRID.ERR_PropertyAccessIgnored)
End If
Case BoundKind.LateMemberAccess
' matches setting ExprResultNotNeeded flag in StatementSemantics/Semantics::InterpretCall
boundInvocation = DirectCast(boundInvocation, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Call)
Case BoundKind.LateInvocation
' matches setting ExprResultNotNeeded flag in StatementSemantics/Semantics::InterpretCall
Dim lateInvocation = DirectCast(boundInvocation, BoundLateInvocation).SetAccessKind(LateBoundAccessKind.Call)
boundInvocation = lateInvocation
' specially for properties being called in Call statement context
If Not lateInvocation.HasErrors AndAlso
TryCast(lateInvocation.MethodOrPropertyGroupOpt, BoundPropertyGroup) IsNot Nothing Then
ReportDiagnostic(diagnostics, boundInvocation.Syntax, ERRID.ERR_PropertyAccessIgnored)
End If
Case BoundKind.ConditionalAccess
Debug.Assert(boundInvocation.Type Is Nothing)
Dim conditionalAccess = DirectCast(boundInvocation, BoundConditionalAccess)
boundInvocation = conditionalAccess.Update(conditionalAccess.Receiver,
conditionalAccess.Placeholder,
ReclassifyInvocationExpressionAsStatement(conditionalAccess.AccessExpression, diagnostics),
GetSpecialType(SpecialType.System_Void, conditionalAccess.Syntax, diagnostics))
End Select
Return boundInvocation
End Function
Private Function BindSingleLineIfStatement(node As SingleLineIfStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
Dim condition As BoundExpression
Dim consequence As BoundBlock
Dim alternative As BoundStatement = Nothing
condition = BindBooleanExpression(node.Condition, diagnostics)
consequence = BindBlock(node, node.Statements, diagnostics)
If node.ElseClause IsNot Nothing Then
alternative = BindBlock(node.ElseClause, node.ElseClause.Statements, diagnostics)
End If
Return New BoundIfStatement(node, condition, consequence, alternative)
End Function
Private Function BindMultiLineIfBlock(node As MultiLineIfBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
' We need to bind the conditions and blocks in lexical order (so that Option Explicit binding
' works right), but build the bound tree in reverse order.
Dim blocks As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance()
Dim conditions As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance()
conditions.Add(BindBooleanExpression(node.IfStatement.Condition, diagnostics))
blocks.Add(BindBlock(node, node.Statements, diagnostics))
For i = 0 To node.ElseIfBlocks.Count - 1
Dim elseIfBlock = node.ElseIfBlocks(i)
conditions.Add(BindBooleanExpression(elseIfBlock.ElseIfStatement.Condition, diagnostics))
blocks.Add(BindBlock(elseIfBlock, elseIfBlock.Statements, diagnostics))
Next
Dim currentAlternative As BoundStatement = Nothing
If node.ElseBlock IsNot Nothing Then
currentAlternative = BindBlock(node.ElseBlock, node.ElseBlock.Statements, diagnostics)
End If
For i = conditions.Count - 1 To 0 Step -1
Dim syntax As VisualBasicSyntaxNode
If i = 0 Then
syntax = node
Else
syntax = node.ElseIfBlocks(i - 1)
End If
currentAlternative = New BoundIfStatement(syntax, conditions(i), blocks(i), currentAlternative)
Next
blocks.Free()
conditions.Free()
Return currentAlternative
End Function
Private Function BindDoLoop(node As DoLoopBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
Dim topCondition As BoundExpression = Nothing
Dim bottomCondition As BoundExpression = Nothing
Dim isTopUntil As Boolean = False
Dim isBottomUntil As Boolean = False
' Bind the top condition, if any.
Dim topConditionSyntax = node.DoStatement.WhileOrUntilClause
If topConditionSyntax IsNot Nothing Then
topCondition = BindBooleanExpression(topConditionSyntax.Condition, diagnostics)
isTopUntil = (topConditionSyntax.Kind = SyntaxKind.UntilClause)
End If
' Get the binder for the body of the loop. This defines the break and continue labels.
Dim loopBodyBinder = GetBinder(DirectCast(node, VisualBasicSyntaxNode))
' Bind the body of the loop.
Dim loopBody As BoundBlock = loopBodyBinder.BindBlock(node, node.Statements, diagnostics)
' Bind the bottom condition, if any.
Dim bottomConditionSyntax = node.LoopStatement.WhileOrUntilClause
If bottomConditionSyntax IsNot Nothing Then
bottomCondition = BindBooleanExpression(bottomConditionSyntax.Condition, diagnostics)
isBottomUntil = (bottomConditionSyntax.Kind = SyntaxKind.UntilClause)
End If
' Create the bound node.
Return New BoundDoLoopStatement(node, topCondition, bottomCondition, isTopUntil, isBottomUntil, loopBody,
continueLabel:=loopBodyBinder.GetContinueLabel(SyntaxKind.ContinueDoStatement),
exitLabel:=loopBodyBinder.GetExitLabel(SyntaxKind.ExitDoStatement),
hasErrors:=topCondition IsNot Nothing AndAlso bottomCondition IsNot Nothing)
End Function
Private Function BindWhileBlock(node As WhileBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
' Bind condition
Dim condition As BoundExpression = BindBooleanExpression(node.WhileStatement.Condition, diagnostics)
' Get the binder for the body of the loop. This defines the break and continue labels.
Dim loopBodyBinder = GetBinder(node)
' Bind the body of the loop.
Dim loopBody As BoundBlock = loopBodyBinder.BindBlock(node, node.Statements, diagnostics)
' Create the bound node.
Return New BoundWhileStatement(node, condition, loopBody,
continueLabel:=loopBodyBinder.GetContinueLabel(SyntaxKind.ContinueWhileStatement),
exitLabel:=loopBodyBinder.GetExitLabel(SyntaxKind.ExitWhileStatement))
End Function
Public Function BindForToBlock(node As ForOrForEachBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
' For statement has its own binding scope since it may introduce iteration variable
' that is visible through the entire For block. It also needs to support Continue/Exit
' Interestingly, control variable is in scope when Limit and Step or the collection are bound,
' but initialized after Limit and Step or collection are evaluated...
Dim loopBinder = Me.GetBinder(node)
Debug.Assert(loopBinder IsNot Nothing)
Dim declaredOrInferredLocalOpt As LocalSymbol = Nothing
Dim isInferredLocal As Boolean = False
Dim controlVariable As BoundExpression = Nothing
Dim hasErrors As Boolean = False
' bind common parts of a for block
hasErrors = loopBinder.BindForBlockParts(node,
node.ForOrForEachStatement.ControlVariable,
declaredOrInferredLocalOpt,
controlVariable,
isInferredLocal,
diagnostics)
' return the specific BoundForToStatement
Return loopBinder.BindForToBlockParts(node,
declaredOrInferredLocalOpt,
controlVariable,
isInferredLocal,
hasErrors,
diagnostics)
End Function
Public Function BindForEachBlock(node As ForOrForEachBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
' For statement has its own binding scope since it may introduce iteration variable
' that is visible through the entire For block. It also needs to support Continue/Exit
' Interestingly, control variable is in scope when Limit and Step or the collection are bound,
' but initialized after Limit and Step or collection are evaluated...
Dim loopBinder = Me.GetBinder(node)
Debug.Assert(loopBinder IsNot Nothing)
Dim declaredOrInferredLocalOpt As LocalSymbol = Nothing
Dim isInferredLocal As Boolean = False
Dim controlVariable As BoundExpression = Nothing
Dim loopBody As BoundBlock = Nothing
Dim nextVariables As ImmutableArray(Of BoundExpression) = Nothing
Dim hasErrors As Boolean = False
' bind common parts of a for block
hasErrors = loopBinder.BindForBlockParts(node,
DirectCast(node.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable,
declaredOrInferredLocalOpt,
controlVariable,
isInferredLocal,
diagnostics)
' return the specific BoundForEachStatement
Return loopBinder.BindForEachBlockParts(node,
declaredOrInferredLocalOpt,
controlVariable,
isInferredLocal,
diagnostics)
End Function
''' <summary>
''' Binds all the common part for ForTo and ForEach loops except the loop body and the next variables.
''' </summary>
''' <param name="node">The node.</param>
''' <param name="controlVariableSyntax">The control variable syntax.</param>
''' <param name="declaredOrInferredLocalOpt">The declared or inferred local symbol.</param>
''' <param name="controlVariable">The control variable.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>true if there were errors; otherwise false</returns>
Private Function BindForBlockParts(node As ForOrForEachBlockSyntax,
controlVariableSyntax As VisualBasicSyntaxNode,
<Out()> ByRef declaredOrInferredLocalOpt As LocalSymbol,
<Out()> ByRef controlVariable As BoundExpression,
<Out()> ByRef isInferredLocal As Boolean,
diagnostics As DiagnosticBag) As Boolean
' Bind control variable
' There are two forms of control variables -
' 1) Control variable declared within the ForStatement
' 2) Expression reference that points to something (local, field...) declared outside of the loop.
Dim hasErrors As Boolean = False
declaredOrInferredLocalOpt = Nothing
isInferredLocal = False
If controlVariableSyntax.Kind = SyntaxKind.VariableDeclarator Then
' This case handles control variables for
' for x as integer = 0 to n
' for each x? in collection
Dim declaratorSyntax = DirectCast(controlVariableSyntax, VariableDeclaratorSyntax)
hasErrors = Not VerifyForControlVariableDeclaration(declaratorSyntax, diagnostics)
' 10.9.3
' 1. If the loop control variable is an identifier with an As clause, the identifier defines a new local variable of
' the type specified in the As clause, scoped to the entire For Each loop.
Dim asClauseOpt = declaratorSyntax.AsClause
Dim names = declaratorSyntax.Names
Debug.Assert(declaratorSyntax.Initializer Is Nothing, "should not have initializer")
Debug.Assert(names.Count = 1, "should be exactly one control variable")
Dim localDeclaration = BindVariableDeclaration(declaratorSyntax,
names(0),
asClauseOpt,
equalsValueOpt:=Nothing,
diagnostics:=diagnostics)
declaredOrInferredLocalOpt = localDeclaration.LocalSymbol
controlVariable = New BoundLocal(declaratorSyntax, declaredOrInferredLocalOpt, declaredOrInferredLocalOpt.Type)
Else
' This case handles control variables for
' for i = 0 to n
' for each Me.MyField in collection
' if it is a simple identifier and Option Infer is on, this might be new local declaration with an
' inferred type.
If controlVariableSyntax.Kind = SyntaxKind.IdentifierName Then
Dim identifier = DirectCast(controlVariableSyntax, IdentifierNameSyntax).Identifier
Dim name = identifier.ValueText
Dim result As LookupResult = LookupResult.GetInstance
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Lookup(result, name, 0, LookupOptions.AllMethodsOfAnyArity, useSiteDiagnostics)
diagnostics.Add(node, useSiteDiagnostics)
' If a local symbol is found then check whether this local corresponds to this identifier. If it does then
' this is local is an inferred local for the for block. This local does not have a type yet. Return the
' local and infer the type when the from/to or for-each collection expressions are available for binding.
If result.IsGood AndAlso
result.Symbols(0).Kind = SymbolKind.Local Then
Dim localSymbol = DirectCast(result.Symbols(0), localSymbol)
If localSymbol.IdentifierToken = identifier Then
' This is an inferred local, we will need to compute its type.
isInferredLocal = True
declaredOrInferredLocalOpt = localSymbol
End If
End If
result.Free()
End If
' it's something else than a simple name (e.g. qualified name ...), so we're going to bind it and
' check if the bound node meets the expectation (e.g. is a field or a local)
If Not isInferredLocal Then
If Not TryBindLoopControlVariable(controlVariableSyntax, controlVariable, diagnostics) Then
hasErrors = True
End If
Else
controlVariable = Nothing
End If
End If
' we cannot bind the loop body and the next variables here, although these nodes are shared between for and for each
' or we loose diagnostics.
Return hasErrors
End Function
''' <summary>
''' Binds loop body and the next variables for ForTo and ForEach loops.
''' </summary>
''' <remarks>
''' The binding of the loop body and the next variables cannot happen before the local type inference has
''' completed, which happens in the specialized binding functions for foreach and for loops. Otherwise we would
''' loose the diagnostics from the type inference.
''' </remarks>
''' <param name="loopBody">The loop body.</param>
''' <param name="nextVariables">The next variables.</param>
Private Sub BindForLoopBodyAndNextControlVariables(
node As ForOrForEachBlockSyntax,
<Out()> ByRef nextVariables As ImmutableArray(Of BoundExpression),
<Out()> ByRef loopBody As BoundBlock,
diagnostics As DiagnosticBag)
' Bind the body of the loop.
loopBody = BindBlock(node, node.Statements, diagnostics)
' bind the variables of the next statement.
' if there is no next statement in this block, the array will be nothing,
' if there is a next statement without variables, the array will be empty, otherwise
' it contains all bound expression in declaration order.
nextVariables = Nothing
Dim endOptSyntax = node.NextStatement
If endOptSyntax IsNot Nothing Then
Dim controlVariableList As SeparatedSyntaxList(Of ExpressionSyntax) = endOptSyntax.ControlVariables
If controlVariableList.IsEmpty Then
' should be the most common case: a next without a variable
nextVariables = ImmutableArray(Of BoundExpression).Empty
ElseIf controlVariableList.Count = 1 Then
' avoid creating an ArrayBuilder for the second most common case, where the control variable
' of the current loop is used.
Dim boundVariable = BindExpression(controlVariableList(0), diagnostics)
boundVariable = ReclassifyAsValue(boundVariable, diagnostics)
nextVariables = ImmutableArray.Create(boundVariable)
Else
Dim nextVariableCount = controlVariableList.Count
Dim nextVariableBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance
Dim currentBinder = Me
For nextVariableIndex = 0 To nextVariableCount - 1
Dim boundVariable = currentBinder.BindExpression(controlVariableList(nextVariableIndex), diagnostics)
boundVariable = ReclassifyAsValue(boundVariable, diagnostics)
nextVariableBuilder.Add(boundVariable)
' due to incremental binding, there might be other binders in between Me and the containing
' StatementListBinder.
' each next variable will be bound with the responsible binder for this for loop
Do
currentBinder = currentBinder.ContainingBinder
Loop While currentBinder IsNot Nothing AndAlso Not (TypeOf (currentBinder) Is StatementListBinder)
If currentBinder IsNot Nothing Then
currentBinder = currentBinder.ContainingBinder
End If
If Not TypeOf currentBinder Is ForOrForEachBlockBinder Then
' this happens for broken code, e.g.
' for each a in arr1
' if goo() then
' for each b in arr2
' next b, a
' end if
Exit For
End If
Next
nextVariables = nextVariableBuilder.ToImmutableAndFree
End If
End If
End Sub
Private Function BindForToBlockParts(
node As ForOrForEachBlockSyntax,
declaredOrInferredLocalOpt As LocalSymbol,
controlVariableOpt As BoundExpression,
isInferredLocal As Boolean,
hasErrors As Boolean,
diagnostics As DiagnosticBag
) As BoundForStatement
Dim forStatement = DirectCast(node.ForOrForEachStatement, ForStatementSyntax)
Dim initialValue As BoundExpression = Nothing
Dim limit As BoundExpression = Nothing
Dim stepValue As BoundExpression = Nothing
If isInferredLocal Then
Debug.Assert(declaredOrInferredLocalOpt IsNot Nothing)
Debug.Assert(controlVariableOpt Is Nothing)
Dim type = InferForFromToVariableType(declaredOrInferredLocalOpt,
forStatement.FromValue,
forStatement.ToValue,
forStatement.StepClause,
initialValue,
limit,
stepValue,
diagnostics)
' Now that we know the type go ahead and set it.
Dim identifier = declaredOrInferredLocalOpt.IdentifierToken
VerifyLocalSymbolNameAndSetType(declaredOrInferredLocalOpt, type, DirectCast(identifier.Parent, VisualBasicSyntaxNode), identifier, diagnostics)
controlVariableOpt = New BoundLocal(forStatement.ControlVariable, declaredOrInferredLocalOpt, type)
End If
Dim targetType = controlVariableOpt.Type
Dim targetTypeIsValid As Boolean = False
If targetType IsNot Nothing AndAlso Not targetType.IsErrorType Then
targetTypeIsValid = IsValidForControlVariableType(node, targetType.GetEnumUnderlyingTypeOrSelf(), diagnostics)
hasErrors = (Not targetTypeIsValid) Or hasErrors
End If
' Bind initial value
If initialValue Is Nothing Then
initialValue = BindValue(forStatement.FromValue, diagnostics)
End If
' Bind limit
If limit Is Nothing Then
limit = BindValue(forStatement.ToValue, diagnostics)
End If
' Bind step
If stepValue Is Nothing Then
Dim stepClause = forStatement.StepClause
If stepClause IsNot Nothing Then
stepValue = BindValue(stepClause.StepValue, diagnostics)
Else
' Spec: "If the step value is omitted, it is implicitly the literal 1, converted to the type of the loop control variable. "
'If there is an error, a special handling required to explain where 1 came from.
stepValue = New BoundLiteral(node,
ConstantValue.Create(1),
Me.GetSpecialType(SpecialType.System_Int32, forStatement, diagnostics))
stepValue.SetWasCompilerGenerated()
End If
End If
If targetTypeIsValid Then
initialValue = ApplyImplicitConversion(initialValue.Syntax, targetType, initialValue, diagnostics)
limit = ApplyImplicitConversion(limit.Syntax, targetType, limit, diagnostics)
stepValue = ApplyConversion(stepValue.Syntax, targetType, stepValue,
isExplicit:=forStatement.StepClause Is Nothing,
diagnostics:=diagnostics)
Else
initialValue = MakeRValueAndIgnoreDiagnostics(initialValue)
limit = MakeRValueAndIgnoreDiagnostics(limit)
stepValue = MakeRValueAndIgnoreDiagnostics(stepValue)
End If
' get special types that are used by the rewriters later on to report use site errors
' TODO: update the types to the ones that get really used by the rewriter. In case of using an index of an user
' defined type there is no need to get the integer type.
Dim integerType = GetSpecialType(SpecialType.System_Int32, node, diagnostics)
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, node, diagnostics)
Dim udfOperators As BoundForToUserDefinedOperators = Nothing
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
' normalize initValue, limit and step to the common type
If Not hasErrors Then
If Not (initialValue.HasErrors OrElse limit.HasErrors OrElse stepValue.HasErrors) AndAlso
targetType.CanContainUserDefinedOperators(useSiteDiagnostics) Then
' Bind user-defined operators that we need.
Dim syntax As VisualBasicSyntaxNode = node.ForOrForEachStatement
Dim leftOperandPlaceholder = New BoundRValuePlaceholder(syntax, targetType).MakeCompilerGenerated()
Dim rightOperandPlaceholder = New BoundRValuePlaceholder(syntax, targetType).MakeCompilerGenerated()
Dim addition As BoundUserDefinedBinaryOperator = BindForLoopUserDefinedOperator(syntax, BinaryOperatorKind.Add, leftOperandPlaceholder, rightOperandPlaceholder, diagnostics)
Dim subtraction As BoundUserDefinedBinaryOperator = BindForLoopUserDefinedOperator(syntax, BinaryOperatorKind.Subtract, leftOperandPlaceholder, rightOperandPlaceholder, diagnostics)
Dim lessThanOrEqual As BoundExpression = BindForLoopUserDefinedOperator(syntax, BinaryOperatorKind.LessThanOrEqual, leftOperandPlaceholder, rightOperandPlaceholder, diagnostics)
If lessThanOrEqual IsNot Nothing Then
lessThanOrEqual = ApplyImplicitConversion(syntax, booleanType, lessThanOrEqual, diagnostics, isOperandOfConditionalBranch:=True).MakeCompilerGenerated()
End If
Dim greaterThanOrEqual As BoundExpression = BindForLoopUserDefinedOperator(syntax, BinaryOperatorKind.GreaterThanOrEqual, leftOperandPlaceholder, rightOperandPlaceholder, diagnostics)
If greaterThanOrEqual IsNot Nothing Then
' Suppress errors if we already reported them for LessThanOrEqual.
greaterThanOrEqual = ApplyImplicitConversion(syntax, booleanType, greaterThanOrEqual,
If(lessThanOrEqual IsNot Nothing AndAlso lessThanOrEqual.HasErrors, New DiagnosticBag(), diagnostics),
isOperandOfConditionalBranch:=True).MakeCompilerGenerated()
End If
If addition IsNot Nothing AndAlso subtraction IsNot Nothing AndAlso lessThanOrEqual IsNot Nothing AndAlso greaterThanOrEqual IsNot Nothing Then
udfOperators = New BoundForToUserDefinedOperators(syntax,
leftOperandPlaceholder, rightOperandPlaceholder,
addition, subtraction,
lessThanOrEqual, greaterThanOrEqual)
Else
hasErrors = True
End If
End If
End If
diagnostics.Add(node, useSiteDiagnostics)
hasErrors = hasErrors OrElse
targetType.IsErrorType OrElse
initialValue.HasErrors OrElse
stepValue.HasErrors OrElse
controlVariableOpt.HasErrors
' Bind the loop body and the next variables
Dim loopBody As BoundBlock = Nothing
Dim nextVariables As ImmutableArray(Of BoundExpression) = Nothing
Me.BindForLoopBodyAndNextControlVariables(node, nextVariables, loopBody, diagnostics)
' Create the bound node.
Return New BoundForToStatement(
node,
initialValue,
limit,
stepValue,
CheckOverflow,
udfOperators,
declaredOrInferredLocalOpt,
controlVariableOpt,
loopBody,
nextVariables,
continueLabel:=GetContinueLabel(SyntaxKind.ContinueForStatement),
exitLabel:=GetExitLabel(SyntaxKind.ExitForStatement),
hasErrors:=hasErrors)
End Function
''' <summary>
''' Can return Nothing in case of failure.
''' </summary>
Private Function BindForLoopUserDefinedOperator(
syntax As VisualBasicSyntaxNode,
opCode As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
diagnostics As DiagnosticBag
) As BoundUserDefinedBinaryOperator
Debug.Assert(opCode = BinaryOperatorKind.Add OrElse opCode = BinaryOperatorKind.Subtract OrElse opCode = BinaryOperatorKind.LessThanOrEqual OrElse opCode = BinaryOperatorKind.GreaterThanOrEqual)
Dim isRelational As Boolean = (opCode = BinaryOperatorKind.LessThanOrEqual OrElse opCode = BinaryOperatorKind.GreaterThanOrEqual)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = OverloadResolution.ResolveUserDefinedBinaryOperator(left, right, opCode, Me, includeEliminatedCandidates:=False,
useSiteDiagnostics:=useSiteDiagnostics)
If diagnostics.Add(syntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
If userDefinedOperator.ResolutionIsLateBound OrElse Not userDefinedOperator.BestResult.HasValue Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ForLoopOperatorRequired2, left.Type, SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(opCode)))
Return Nothing
End If
Dim bestCandidate As OverloadResolution.Candidate = userDefinedOperator.BestResult.Value.Candidate
If Not bestCandidate.Parameters(0).Type.IsSameTypeIgnoringAll(left.Type) OrElse
Not bestCandidate.Parameters(1).Type.IsSameTypeIgnoringAll(left.Type) OrElse
(Not isRelational AndAlso Not bestCandidate.ReturnType.IsSameTypeIgnoringAll(left.Type)) Then
If isRelational Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_UnacceptableForLoopRelOperator2, bestCandidate.UnderlyingSymbol,
If(bestCandidate.IsLifted,
left.Type.GetNullableUnderlyingTypeOrSelf(),
left.Type))
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_UnacceptableForLoopOperator2, bestCandidate.UnderlyingSymbol,
If(bestCandidate.IsLifted,
left.Type.GetNullableUnderlyingTypeOrSelf(),
left.Type))
End If
Return Nothing
End If
Dim result As BoundUserDefinedBinaryOperator = BindUserDefinedNonShortCircuitingBinaryOperator(syntax, opCode, left, right, userDefinedOperator, diagnostics).MakeCompilerGenerated()
result.UnderlyingExpression.MakeCompilerGenerated()
Return result
End Function
' Verify that control variable can actually be used as a control variable
Private Shared Function IsValidForControlVariableType(node As ForOrForEachBlockSyntax,
targetType As TypeSymbol,
diagnostics As DiagnosticBag) As Boolean
' if it's a nullable type, simply unwrap it (no recursion needed because nullables cannot be nested)
If targetType.IsNullableType Then
targetType = targetType.GetNullableUnderlyingType.GetEnumUnderlyingTypeOrSelf
End If
If targetType.IsNumericType Then
Return True
End If
If targetType.IsObjectType Then
Return True
End If
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If targetType.IsIntrinsicOrEnumType OrElse Not targetType.CanContainUserDefinedOperators(useSiteDiagnostics) Then
diagnostics.Add(DirectCast(node.ForOrForEachStatement, ForStatementSyntax).ControlVariable, useSiteDiagnostics)
ReportDiagnostic(diagnostics, DirectCast(node.ForOrForEachStatement, ForStatementSyntax).ControlVariable, ERRID.ERR_ForLoopType1, targetType)
Return False
End If
diagnostics.Add(DirectCast(node.ForOrForEachStatement, ForStatementSyntax).ControlVariable, useSiteDiagnostics)
Return True
End Function
Private Function BindForEachBlockParts(
node As ForOrForEachBlockSyntax,
declaredOrInferredLocalOpt As LocalSymbol,
controlVariableOpt As BoundExpression,
isInferredLocal As Boolean,
diagnostics As DiagnosticBag
) As BoundForEachStatement
Dim forEachStatement = DirectCast(node.ForOrForEachStatement, ForEachStatementSyntax)
Dim currentType As TypeSymbol = Nothing
Dim isEnumerable As Boolean = False
Dim needToDispose As Boolean = False
Dim isOrInheritsFromOrImplementsIDisposable As Boolean = False
Dim boundGetEnumeratorCall As BoundExpression = Nothing
Dim boundEnumeratorPlaceholder As BoundLValuePlaceholder = Nothing
Dim boundMoveNextCall As BoundExpression = Nothing
Dim boundCurrentAccess As BoundExpression = Nothing
Dim collectionPlaceholder As BoundRValuePlaceholder = Nothing
Dim boundDisposeCondition As BoundExpression = Nothing
Dim boundDisposeCast As BoundExpression = Nothing
Dim boundCurrentConversion As BoundExpression = Nothing
Dim boundCurrentPlaceholder As BoundRValuePlaceholder = Nothing
Dim collection As BoundExpression = Nothing
If isInferredLocal Then
Debug.Assert(declaredOrInferredLocalOpt IsNot Nothing)
Debug.Assert(controlVariableOpt Is Nothing)
Dim type = InferForEachVariableType(declaredOrInferredLocalOpt,
forEachStatement.Expression,
collection,
currentType,
isEnumerable,
boundGetEnumeratorCall,
boundEnumeratorPlaceholder,
boundMoveNextCall,
boundCurrentAccess,
collectionPlaceholder,
needToDispose,
isOrInheritsFromOrImplementsIDisposable,
diagnostics)
' Now that we know the type go ahead and set it.
Dim identifier = declaredOrInferredLocalOpt.IdentifierToken
VerifyLocalSymbolNameAndSetType(declaredOrInferredLocalOpt, type, DirectCast(identifier.Parent, VisualBasicSyntaxNode), identifier, diagnostics)
controlVariableOpt = New BoundLocal(forEachStatement.ControlVariable, declaredOrInferredLocalOpt, type)
End If
If collection Is Nothing Then
' bind the expression that describes the collection to iterate over
collection = BindValue(forEachStatement.Expression, diagnostics)
If Not collection.IsLValue AndAlso Not collection.IsNothingLiteral Then
collection = MakeRValue(collection, diagnostics)
End If
' check if the collection is valid for a for each statement
collection = InterpretForEachStatementCollection(collection,
currentType,
isEnumerable,
boundGetEnumeratorCall,
boundEnumeratorPlaceholder,
boundMoveNextCall,
boundCurrentAccess,
collectionPlaceholder,
needToDispose,
isOrInheritsFromOrImplementsIDisposable,
diagnostics)
End If
Dim currentPlaceholderType = currentType
Dim collectionType = collection.Type
If Not (collectionType.IsArrayType AndAlso DirectCast(collectionType, ArrayTypeSymbol).IsSZArray) Then
Dim isStringForEach = collectionType.IsStringType
If Not isStringForEach AndAlso collection.Kind = BoundKind.Conversion Then
Dim conversion As BoundConversion = DirectCast(collection, BoundConversion)
If Not conversion.ExplicitCastInCode Then
Dim unconvertedCollectionType = conversion.Operand.Type
isStringForEach = unconvertedCollectionType IsNot Nothing AndAlso unconvertedCollectionType.IsStringType
End If
End If
If isStringForEach Then
If currentPlaceholderType IsNot Nothing AndAlso currentPlaceholderType.SpecialType <> SpecialType.System_Char Then
currentPlaceholderType = GetSpecialType(SpecialType.System_Char, node, diagnostics)
End If
End If
End If
'
' Now we're already creating some bound nodes that will be used in the local rewriter to report possible
' diagnostics early and to reuse the code that exists in the binder.
'
Dim collectionSyntax = collection.Syntax
' Note: the conversion is from the array's element type (if rank = 1), char, or the return type of
' the current's get method
If currentType IsNot Nothing AndAlso Not controlVariableOpt.HasErrors Then
Dim controlVariableType = controlVariableOpt.Type
If Not (controlVariableType.IsErrorType OrElse currentType.IsErrorType) Then
boundCurrentPlaceholder = New BoundRValuePlaceholder(collectionSyntax, currentPlaceholderType)
' "Current" is converted to the type of the control variable as if
' it were an explicit cast. This language rule exists because there is
' no way to write a cast, and the type of the IEnumerator.Current is Object,
' which would make
'
' Dim I, A() As Integer : For Each I in A : Next
'
' invalid in strict mode.
boundCurrentConversion = ApplyConversion(collectionSyntax,
controlVariableType,
boundCurrentPlaceholder,
isExplicit:=True,
diagnostics:=diagnostics)
boundCurrentConversion.SetWasCompilerGenerated()
End If
' for multidimensional arrays make additional check that array element is castable to iteration variable type
' we need to do this because multidimensional arrays only implement nongeneric IEnumerable
' so the cast from Current --> control variable will statically succeed (since Current returns object)
' We however can know the element type and may know that under no condition the cast will work at run time
' So we will check that here.
If collection.Type.IsArrayType Then
Dim elementType = DirectCast(collection.Type, ArrayTypeSymbol).ElementType
If Not elementType.IsErrorType AndAlso Not controlVariableType.IsErrorType Then
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conv = Conversions.ClassifyConversion(elementType, controlVariableType, useSiteDiagnostics).Key
If diagnostics.Add(collectionSyntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
ElseIf Not Conversions.ConversionExists(conv) Then
ReportDiagnostic(diagnostics, collectionSyntax, ERRID.ERR_TypeMismatch2, elementType, controlVariableType)
End If
End If
End If
End If
' in case the enumerator needs to be possibly disposed, create the bound nodes for the condition that checks
' if Dispose() needs to be called. This bound expression will contain a placeholder for the enumerator that gets
' replaced in the local rewriting.
If needToDispose Then
' no need to report use site errors here, this was already done in InterpretForEachStatementCollection
Dim idisposableType = Compilation.GetSpecialType(SpecialType.System_IDisposable)
' needToDispose can only be true if boundGetEnumeratorCall had no errors (see InterpretForEachStatementCollection)
Dim enumeratorType = boundGetEnumeratorCall.Type
' IDisposable is implemented, which means there must be a check if the enumerator is not nothing
' will be used in code: "If e IsNot Nothing Then"
If isOrInheritsFromOrImplementsIDisposable Then
If Not (enumeratorType.IsValueType) Then
boundDisposeCondition = BindIsExpression(boundEnumeratorPlaceholder,
New BoundLiteral(collectionSyntax, ConstantValue.Nothing, Nothing),
collectionSyntax, True, diagnostics)
boundDisposeCast = ApplyConversion(collectionSyntax, idisposableType, boundEnumeratorPlaceholder, isExplicit:=True, diagnostics:=diagnostics)
End If
Else
Debug.Assert(enumeratorType.SpecialType = SpecialType.System_Collections_IEnumerator)
' Instead of if TypeOf(e) is IDisposable, we'll do a TryCast(e, IDisposable) and call Dispose if the result
' was not Nothing.
' create TryCast
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conversionKind As conversionKind = Conversions.ClassifyTryCastConversion(enumeratorType, idisposableType, useSiteDiagnostics)
If diagnostics.Add(collectionSyntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
boundDisposeCast = New BoundTryCast(collectionSyntax, boundEnumeratorPlaceholder.MakeRValue(), conversionKind, idisposableType, Nothing)
boundDisposeCondition = BindIsExpression(boundDisposeCast,
New BoundLiteral(collectionSyntax, ConstantValue.Nothing, Nothing),
collectionSyntax, True, diagnostics)
End If
End If
' Bind the loop body and the next variables
Dim loopBody As BoundBlock = Nothing
Dim nextVariables As ImmutableArray(Of BoundExpression) = Nothing
Me.BindForLoopBodyAndNextControlVariables(node, nextVariables, loopBody, diagnostics)
Dim enumeratorInfo = New ForEachEnumeratorInfo(boundGetEnumeratorCall,
boundMoveNextCall,
boundCurrentAccess,
needToDispose,
isOrInheritsFromOrImplementsIDisposable,
boundDisposeCondition,
boundDisposeCast,
boundCurrentConversion,
boundEnumeratorPlaceholder,
boundCurrentPlaceholder,
collectionPlaceholder)
Return New BoundForEachStatement(node,
collection,
enumeratorInfo,
declaredOrInferredLocalOpt, controlVariableOpt, loopBody, nextVariables,
continueLabel:=GetContinueLabel(SyntaxKind.ContinueForStatement),
exitLabel:=GetExitLabel(SyntaxKind.ExitForStatement))
End Function
''' <summary>
''' Verifies for control variable declaration and outputs diagnostics as needed.
''' </summary>
''' <param name="variableDeclarator">The variable declarator.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Shared Function VerifyForControlVariableDeclaration(variableDeclarator As VariableDeclaratorSyntax, diagnostics As DiagnosticBag) As Boolean
' Check variable declaration syntax if present
Debug.Assert(variableDeclarator.Names.Count = 1, "should be exactly one control variable")
Dim identifier = variableDeclarator.Names(0)
' nullable type inference is not supported
If variableDeclarator.AsClause Is Nothing AndAlso
identifier.Nullable.Node IsNot Nothing Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_NullableTypeInferenceNotSupported)
Return False
End If
' specifying array bounds is not valid for control variable declarations
If identifier.ArrayBounds IsNot Nothing Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_ForCtlVarArraySizesSpecified)
Return False
End If
Return True
End Function
''' <summary>
''' This function tries to bind the given controlVariableSyntax.
''' If it was an identifier of a valid target, the bound node is written to controlVariable and true is returned.
''' If something else was bound, that is not legal as a control variable (e.g. a property), a BoundBadNode is written
''' to controlVariable and false is returned.
''' If nothing declared was found, false is returned and controlVariable is set to nothing. In this case it's safe to
''' create a new local for the loop node.
''' </summary>
Private Function TryBindLoopControlVariable(
controlVariableSyntax As VisualBasicSyntaxNode,
<Out()> ByRef controlVariable As BoundExpression,
diagnostics As DiagnosticBag
) As Boolean
Debug.Assert(controlVariableSyntax.Kind <> SyntaxKind.VariableDeclarator)
controlVariable = BindExpression(DirectCast(controlVariableSyntax, ExpressionSyntax), diagnostics)
controlVariable = ReclassifyAsValue(controlVariable, diagnostics)
If controlVariable.HasErrors Then
' VB Spec 10.9.3 2.2: 2.2. Otherwise, if it is classified as anything other than a type
' or a variable, it is a compile-error.
controlVariable = BadExpression(controlVariable)
Return False
End If
' VB Spec 10.9.3 2.1: If the result of this resolution is classified as a variable, then
' the loop control variable is that variable.
If Not VerifyForLoopControlReference(controlVariable, diagnostics) Then
controlVariable = New BoundBadExpression(controlVariableSyntax,
LookupResultKind.NotAVariable,
ImmutableArray(Of Symbol).Empty,
ImmutableArray.Create(controlVariable),
controlVariable.Type,
hasErrors:=True)
Return False
End If
Return True
End Function
''' <summary>
''' If the control variable was bound to a non bad expression, this function checks if the
''' bound expression is a variable and reports diagnostics appropriately.
''' It reports the errors from 10.9.3 2.2
''' </summary>
''' <param name="controlVariable">The control variable.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function VerifyForLoopControlReference(controlVariable As BoundExpression, diagnostics As DiagnosticBag) As Boolean
Dim isLValue As Boolean
' A property reference is not allowed as the control variable of any
' kind of For statement.
If controlVariable.IsPropertyOrXmlPropertyAccess() Then
ReportDiagnostic(diagnostics, controlVariable.Syntax, ERRID.ERR_LoopControlMustNotBeProperty)
Return False
Else
isLValue = controlVariable.IsLValue()
End If
If Not isLValue Then
If Not controlVariable.HasErrors Then
ReportAssignmentToRValue(controlVariable, diagnostics)
End If
Return False
End If
If Not controlVariable.HasErrors AndAlso IsInAsyncContext() AndAlso
SeenAwaitVisitor.SeenAwaitIn(controlVariable, diagnostics) Then
ReportDiagnostic(diagnostics, controlVariable.Syntax, ERRID.ERR_LoopControlMustNotAwait)
Return False
End If
Return True
End Function
Private Class SeenAwaitVisitor
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
Private _seenAwait As Boolean
Private Sub New()
End Sub
Public Shared Function SeenAwaitIn(node As BoundNode, diagnostics As DiagnosticBag) As Boolean
Dim visitor = New SeenAwaitVisitor()
Try
visitor.Visit(node)
Catch ex As CancelledByStackGuardException
ex.AddAnError(diagnostics)
End Try
Return visitor._seenAwait
End Function
Public Overrides Function Visit(node As BoundNode) As BoundNode
If _seenAwait Then
Return Nothing
End If
Return MyBase.Visit(node)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
' Do not dive into lambdas.
Return Nothing
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
_seenAwait = True
Return Nothing
End Function
End Class
''' <summary>
''' Verifies that the collection is either a string, and array or matches the design pattern criteria and reports
''' diagnostics appropriately.
''' </summary>
''' <param name="collection">The collection of the for each statement.</param>
''' <param name="currentType">If the collection meets all criteria, currentType contains the type of the element from
''' the collection that get's returned by the current property.</param>
''' <param name="isEnumerable">if set to <c>true</c>, the collection is enumerable (matches design pattern, IEnumerable
''' or IEnumerable(Of T); otherwise (string or arrays) it's set to false.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The collection which might have been converted to IEnumerable or IEnumerable(Of T) if needed.</returns>
Private Function InterpretForEachStatementCollection(
collection As BoundExpression,
<Out()> ByRef currentType As TypeSymbol,
<Out()> ByRef isEnumerable As Boolean,
<Out()> ByRef boundGetEnumeratorCall As BoundExpression,
<Out()> ByRef boundEnumeratorPlaceholder As BoundLValuePlaceholder,
<Out()> ByRef boundMoveNextCall As BoundExpression,
<Out()> ByRef boundCurrentAccess As BoundExpression,
<Out()> ByRef collectionPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef needToDispose As Boolean,
<Out()> ByRef isOrInheritsFromOrImplementsIDisposable As Boolean,
diagnostics As DiagnosticBag
) As BoundExpression
currentType = Nothing
isEnumerable = False
needToDispose = False
isOrInheritsFromOrImplementsIDisposable = False
boundGetEnumeratorCall = Nothing
boundEnumeratorPlaceholder = Nothing
boundMoveNextCall = Nothing
boundCurrentAccess = Nothing
collectionPlaceholder = Nothing
If collection.HasErrors Then
Return collection
End If
Dim collectionType As TypeSymbol = collection.Type
Dim collectionSyntax = collection.Syntax
Dim targetCollectionType As NamedTypeSymbol = Nothing
' If the collection matches the design pattern, use that.
' Otherwise, if the collection implements IEnumerable, convert it
' to IEnumerable (which matches the design pattern).
'
' The design pattern is preferred to the interface implementation
' because it is more efficient.
Dim interfaceSpecialType As SpecialType = SpecialType.None
Dim detailedDiagnostics = DiagnosticBag.GetInstance
If MatchesForEachCollectionDesignPattern(collectionType, collection,
currentType,
boundGetEnumeratorCall,
boundEnumeratorPlaceholder,
boundMoveNextCall,
boundCurrentAccess,
collectionPlaceholder,
detailedDiagnostics) Then
diagnostics.AddRange(detailedDiagnostics)
' TODO(rbeckers) check if the long note about spurious errors in Dev10 (statement_semantics.cpp, line 5250) needs
' to be copied.
' We only pass in a temporary diagnostic bag into this method. The method itself only adds to it in case of
' ambiguous lookups or a failed overload resolution for the current property access.
isEnumerable = True
If collectionType.IsArrayType AndAlso DirectCast(collectionType, ArrayTypeSymbol).IsSZArray Then
Dim arrayType = DirectCast(collectionType, ArrayTypeSymbol)
currentType = arrayType.ElementType
' if IEnumerable is missing, there should be no diagnostic, because in this case it would not be needed to
' generate IL. The only side effect would be that the ConvertedType of the semantic info does not show
' IEnumerable.
Dim ienumerable = Compilation.GetSpecialType(SpecialType.System_Collections_IEnumerable)
' this is only needed to report the converted type of the semantic model
' to be IEnumerable in case of arrays. The resulting bound conversion will be thrown away in the
' rewriter.
targetCollectionType = ienumerable
' TODO: consider special casing strings and one dimensional arrays in the semantic info
End If
Else
' using a temporary diagnostic bag to only report use site errors for IEnumerable or IEnumerable(Of T) if they are used.
Dim ienumerableUseSiteDiagnostics = DiagnosticBag.GetInstance
Dim genericIEnumerable = GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T, collectionSyntax, ienumerableUseSiteDiagnostics)
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not collection.IsNothingLiteral AndAlso
Not collectionType.IsArrayType AndAlso
IsOrInheritsFromOrImplementsInterface(collectionType, genericIEnumerable, useSiteDiagnostics, matchingInterfaces) Then
diagnostics.Add(collectionSyntax, useSiteDiagnostics)
Debug.Assert(matchingInterfaces.Count > 0)
isEnumerable = True
targetCollectionType = matchingInterfaces(0)
' merge diagnostics for IEnumerable(Of T)
diagnostics.AddRange(ienumerableUseSiteDiagnostics)
ienumerableUseSiteDiagnostics.Free()
If matchingInterfaces.Count > 1 Then
' matchingInterfaces is a hash set, so it's enough to check if the count is more than one.
' Duplicates found while analyzing type parameter constraints do not occur this way like in Dev10.
ReportDiagnostic(diagnostics,
collectionSyntax,
ErrorFactory.ErrorInfo(ERRID.ERR_ForEachAmbiguousIEnumerable1,
collectionType))
detailedDiagnostics.Free()
Return New BoundBadExpression(collectionSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray.Create(collection),
collectionType,
hasErrors:=True)
End If
interfaceSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T
Else
ienumerableUseSiteDiagnostics.Clear()
Dim ienumerable = GetSpecialType(SpecialType.System_Collections_IEnumerable, collectionSyntax, ienumerableUseSiteDiagnostics)
If ((collection.IsNothingLiteral OrElse collectionType.IsObjectType) AndAlso Me.OptionStrict <> OptionStrict.On) OrElse
(Not collection.IsNothingLiteral AndAlso Not collectionType.IsArrayType AndAlso IsOrInheritsFromOrImplementsInterface(collectionType, ienumerable, useSiteDiagnostics, matchingInterfaces)) Then
Debug.Assert(collection.IsNothingLiteral OrElse collectionType.IsObjectType OrElse (matchingInterfaces.First = ienumerable AndAlso matchingInterfaces.Count = 1))
diagnostics.Add(collectionSyntax, useSiteDiagnostics)
isEnumerable = True
targetCollectionType = ienumerable
interfaceSpecialType = SpecialType.System_Collections_IEnumerable
' merge diagnostics for IEnumerable
diagnostics.AddRange(ienumerableUseSiteDiagnostics)
ienumerableUseSiteDiagnostics.Free()
Else
Debug.Assert(collectionType IsNot Nothing OrElse collection.IsNothingLiteral AndAlso Me.OptionStrict = OptionStrict.On)
diagnostics.Add(collectionSyntax, useSiteDiagnostics)
If collection.IsNothingLiteral Then
' in case of option strict on we need to reclassify the nothing literal
collection = MakeRValue(collection, diagnostics)
collectionType = collection.Type
End If
' Show detailed errors for ambiguous lookups or failed overload resolution in case they are available,
' otherwise report the default error "xyz does not match design pattern".
If detailedDiagnostics.HasAnyErrors Then
diagnostics.AddRange(detailedDiagnostics)
Else
ReportDiagnostic(diagnostics,
collectionSyntax,
ErrorFactory.ErrorInfo(ERRID.ERR_ForEachCollectionDesignPattern1,
collectionType))
End If
detailedDiagnostics.Free()
ienumerableUseSiteDiagnostics.Free()
Return New BoundBadExpression(collectionSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray.Create(collection),
collectionType,
hasErrors:=True)
End If
End If
End If
detailedDiagnostics.Free()
' in case one of the IEnumerable interfaces are used, we'll need to cast to it.
' this needs to happen before creating the bound calls, to force a boxing of collections that are value types.
If targetCollectionType IsNot Nothing Then
collection = ApplyImplicitConversion(collectionSyntax, targetCollectionType, collection, diagnostics)
End If
If isEnumerable Then
If interfaceSpecialType <> SpecialType.None Then
Dim member As Symbol
Dim specialTypeMember As Symbol
'
' GetEnumerator
'
If interfaceSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T Then
specialTypeMember = GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator,
collectionSyntax,
diagnostics)
If specialTypeMember IsNot Nothing AndAlso specialTypeMember.GetUseSiteErrorInfo Is Nothing AndAlso Not targetCollectionType.IsErrorType Then
member = DirectCast(targetCollectionType, SubstitutedNamedType).GetMemberForDefinition(specialTypeMember)
Else
member = Nothing
End If
Else
member = GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator,
collectionSyntax,
diagnostics)
End If
If member IsNot Nothing AndAlso member.GetUseSiteErrorInfo Is Nothing Then
collectionPlaceholder = New BoundRValuePlaceholder(collectionSyntax,
If(collectionType IsNot Nothing AndAlso collectionType.IsStringType, collectionType, collection.Type))
Dim methodOrPropertyGroup As BoundMethodOrPropertyGroup
methodOrPropertyGroup = New BoundMethodGroup(collectionSyntax,
Nothing,
ImmutableArray.Create(DirectCast(member, MethodSymbol)),
LookupResultKind.Good,
collectionPlaceholder,
QualificationKind.QualifiedViaValue)
boundGetEnumeratorCall = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
diagnostics)
Dim enumeratorType = boundGetEnumeratorCall.Type
boundEnumeratorPlaceholder = New BoundLValuePlaceholder(collectionSyntax,
enumeratorType)
'
' MoveNext
'
member = GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext,
collectionSyntax,
diagnostics)
If member IsNot Nothing AndAlso member.GetUseSiteErrorInfo Is Nothing Then
methodOrPropertyGroup = New BoundMethodGroup(collectionSyntax,
Nothing,
ImmutableArray.Create(DirectCast(member, MethodSymbol)),
LookupResultKind.Good,
boundEnumeratorPlaceholder,
QualificationKind.QualifiedViaValue)
boundMoveNextCall = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
diagnostics)
End If
'
' Current
'
If interfaceSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T Then
specialTypeMember = GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerator_T__Current,
collectionSyntax,
diagnostics)
If specialTypeMember IsNot Nothing AndAlso specialTypeMember.GetUseSiteErrorInfo Is Nothing AndAlso Not enumeratorType.IsErrorType Then
member = DirectCast(enumeratorType, SubstitutedNamedType).GetMemberForDefinition(specialTypeMember)
Else
member = Nothing
End If
Else
member = GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current,
collectionSyntax,
diagnostics)
End If
If member IsNot Nothing AndAlso member.GetUseSiteErrorInfo Is Nothing Then
methodOrPropertyGroup = New BoundPropertyGroup(collectionSyntax,
ImmutableArray.Create(DirectCast(member, PropertySymbol)),
LookupResultKind.Good,
boundEnumeratorPlaceholder,
QualificationKind.QualifiedViaValue)
boundCurrentAccess = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
diagnostics)
currentType = boundCurrentAccess.Type
End If
End If
End If
Debug.Assert(interfaceSpecialType <> SpecialType.None OrElse Not collectionType.IsStringType OrElse currentType.SpecialType = SpecialType.System_Char)
' if it's enumerable, we'll need to check if the enumerator is disposable.
Dim idisposable = GetSpecialType(SpecialType.System_IDisposable, collectionSyntax, diagnostics)
If (idisposable IsNot Nothing AndAlso Not idisposable.IsErrorType) AndAlso
Not boundGetEnumeratorCall.HasErrors AndAlso Not boundGetEnumeratorCall.Type.IsErrorType Then
Dim getEnumeratorReturnType = boundGetEnumeratorCall.Type
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conversionKind = Conversions.ClassifyDirectCastConversion(getEnumeratorReturnType, idisposable, useSiteDiagnostics)
diagnostics.Add(collectionSyntax, useSiteDiagnostics)
isOrInheritsFromOrImplementsIDisposable = Conversions.IsWideningConversion(conversionKind)
If isOrInheritsFromOrImplementsIDisposable OrElse
getEnumeratorReturnType.SpecialType = SpecialType.System_Collections_IEnumerator Then
' do not actually generate dispose calls in IL
' Dev10 does the same thing (StatementSemantics.cpp, Line 5678++)
' this is true even for multidimensional arrays that are handled through the design pattern.
Debug.Assert(collectionType IsNot Nothing OrElse OptionStrict <> OptionStrict.On AndAlso collection.Kind = BoundKind.Conversion AndAlso DirectCast(collection, BoundConversion).Operand.IsNothingLiteral)
If collectionType Is Nothing OrElse Not collectionType.IsArrayType Then
needToDispose = True
End If
End If
End If
End If
Return collection
End Function
''' <summary>
''' Checks if the type of the collection matches the for each collection design pattern.
''' </summary>
''' <remarks>
''' The rules are that the collection type must have an accessible GetEnumerator method that takes no parameters and
''' returns a type that has both:
''' - an accessible MoveNext method that takes no parameters and returns a Boolean
''' - an accessible Current property that takes no parameters and is not WriteOnly
'''
''' NOTE: this function ONLY checks for a function named "GetEnumerator" with the appropriate properties.
''' In the spec $10.9 it has these conditions: a type C is a "collection type" if one of
''' (1) it satisfies MatchesForEachCollectionDesignPattern (i.e. has a method named GetEnumerator() which
''' returns a type with MoveNext/Current); or
''' (2) it implements System.Collections.Generic.IEnumerable(Of T); or
''' (3) it implements System.Collections.IEnumerable.
'''
''' This function ONLY checks for part (1). Callers are expected to check for (2)/(3) themselves. The
''' scenario where something satisfies (2/3) but not (1) is
''' Class C
''' Implements IEnumerable
''' Function g1() as IEnumerator implements IEnumerable.GetEnumerator : End Function
'''
''' Clearly this class does not have a method _named_ GetEnumerator, but it does implement IEnumerable.
''' </remarks>
''' <param name="collectionType">The type of the for each collection.</param>
''' <param name="collection">The bound collection expression.</param>
''' <param name="currentType">Return type of the property named "Current" if found.</param>
''' <param name="boundGetEnumeratorCall">A bound call to GetEnumerator on the collection if found.</param>
''' <param name="boundEnumeratorPlaceholder">A bound placeholder value for the collection local if GetEnumerator
''' was bound successful</param>
''' <param name="boundMoveNextCall">A bound call to MoveNext on the instance returned by GetEnumerator if found.</param>
''' <param name="boundCurrentAccess">A bound property access for "Current" on the instance returned by GetEnumerator if found.</param>
''' <param name="collectionPlaceholder">A placeholder for the collection expression.</param>
''' <param name="temporaryDiagnostics">An empty diagnostic bag to capture diagnostics that have to be reported if the
''' collection matches the design pattern and that can be used instead of the generic error message in case non of the
''' for each collection criteria match.</param>
''' <returns>If all required methods have been successfully looked up and bound, true is being returned; otherwise false.
''' </returns>
Private Function MatchesForEachCollectionDesignPattern(
collectionType As TypeSymbol,
collection As BoundExpression,
<Out()> ByRef currentType As TypeSymbol,
<Out()> ByRef boundGetEnumeratorCall As BoundExpression,
<Out()> ByRef boundEnumeratorPlaceholder As BoundLValuePlaceholder,
<Out()> ByRef boundMoveNextCall As BoundExpression,
<Out()> ByRef boundCurrentAccess As BoundExpression,
<Out()> ByRef collectionPlaceholder As BoundRValuePlaceholder,
temporaryDiagnostics As DiagnosticBag
) As Boolean
Debug.Assert(temporaryDiagnostics.IsEmptyWithoutResolution)
currentType = Nothing
boundGetEnumeratorCall = Nothing
boundEnumeratorPlaceholder = Nothing
boundMoveNextCall = Nothing
boundCurrentAccess = Nothing
' This method will add diagnostics (errors and warnings) to the given diagnostic bag. It might clean it while processing
' the collection type to reduce noise which is why only a new/empty diagnostic bag should be passed to this method.
'
' The diagnostics returned by this method should be added to the general diagnostic bag in case of a successful match
' of the collection design pattern to e.g. report warnings.
' If the collection does not match the collection design pattern and the collection is not and does not implement or
' inherits IEnumerable(Of T) or IEnumerable then the diagnostics can be used to give a more detailed reason instead
' of the generic "collection {0} does not match design pattern".
' To provide more detailed information that is close to the output of Dev10 we are collection diagnostics from
' ambiguous lookups and from binding the current property get access.
Dim collectionSyntax = collection.Syntax
If collection.IsNothingLiteral OrElse
(collectionType.Kind <> SymbolKind.ArrayType AndAlso
collectionType.Kind <> SymbolKind.NamedType AndAlso
collectionType.Kind <> SymbolKind.TypeParameter) Then
' Dev10 checked for !IsClassInterfaceRecordOrGenericParamType which is equivalent to a named type in Roslyn
Return False
End If
'
' GetEnumerator
'
' first, get GetEnumerator function that takes no arguments, also search in extension methods
Dim lookupResult As New lookupResult()
If Not GetMemberIfMatchesRequirements(WellKnownMemberNames.GetEnumeratorMethodName,
collectionType,
s_isFunctionWithoutArguments,
lookupResult,
collectionSyntax,
temporaryDiagnostics) Then
Return False
End If
Debug.Assert(lookupResult.IsGood)
collectionPlaceholder = New BoundRValuePlaceholder(collectionSyntax, collection.Type)
' bind the call to GetEnumerator (incl. overload resolution, handling of param arrays, optional parameters, ...)
Dim methodOrPropertyGroup As BoundMethodOrPropertyGroup = CreateBoundMethodGroup(collectionSyntax,
lookupResult,
LookupOptions.AllMethodsOfAnyArity,
collectionPlaceholder,
Nothing,
QualificationKind.QualifiedViaValue)
boundGetEnumeratorCall = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
temporaryDiagnostics)
If boundGetEnumeratorCall.HasErrors Then
temporaryDiagnostics.Clear()
Return False
End If
Dim enumeratorType As TypeSymbol = boundGetEnumeratorCall.Type
boundEnumeratorPlaceholder = New BoundLValuePlaceholder(collectionSyntax, enumeratorType)
'
' MoveNext
'
' try lookup an accessible MoveNext function in the return type of GetEnumerator that takes no parameters and
' returns a boolean.
If Not GetMemberIfMatchesRequirements(WellKnownMemberNames.MoveNextMethodName,
enumeratorType,
s_isFunctionWithoutArguments,
lookupResult,
collectionSyntax,
temporaryDiagnostics) Then
Return False
End If
Debug.Assert(lookupResult.IsGood)
' bind the call to MoveNext (incl. overload resolution, handling of param arrays, optional parameters, ...)
methodOrPropertyGroup = CreateBoundMethodGroup(collectionSyntax,
lookupResult,
LookupOptions.AllMethodsOfAnyArity,
boundEnumeratorPlaceholder,
Nothing,
QualificationKind.QualifiedViaValue)
boundMoveNextCall = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
temporaryDiagnostics)
If boundMoveNextCall.HasErrors OrElse
boundMoveNextCall.Kind <> BoundKind.Call OrElse
DirectCast(boundMoveNextCall, BoundCall).Method.OriginalDefinition.ReturnType.SpecialType <> SpecialType.System_Boolean Then
' Dev10 does not accept a MoveNext with a constructed return type, even if it is a boolean.
temporaryDiagnostics.Clear()
Return False
End If
'
' Current
'
' try lookup an accessible and readable property named Current that takes no parameters.
If Not GetMemberIfMatchesRequirements(WellKnownMemberNames.CurrentPropertyName,
enumeratorType,
s_isReadablePropertyWithoutArguments,
lookupResult,
collectionSyntax,
temporaryDiagnostics) Then
Return False
End If
Debug.Assert(lookupResult.IsGood)
' bind the call to Current (incl. overload resolution, handling of param arrays, optional parameters, ...)
methodOrPropertyGroup = New BoundPropertyGroup(collectionSyntax,
lookupResult.Symbols.ToDowncastedImmutable(Of PropertySymbol),
lookupResult.Kind,
boundEnumeratorPlaceholder,
QualificationKind.QualifiedViaValue)
boundCurrentAccess = CreateBoundInvocationExpressionFromMethodOrPropertyGroup(collectionSyntax,
methodOrPropertyGroup,
temporaryDiagnostics)
' the requirement is a "readable" property that takes no parameters, but the get property could be inaccessible
' and then binding a property access will fail.
If boundCurrentAccess.HasErrors Then
Return False
End If
currentType = boundCurrentAccess.Type
Return True
End Function
''' <summary>
''' Creates a BoundCall or BoundPropertyAccess from a MethodOrPropertyGroup.
''' </summary>
''' <remarks>
''' This is not a general purpose helper!
''' </remarks>
''' <param name="syntax">The syntax node.</param>
''' <param name="methodOrPropertyGroup">The method or property group.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Function CreateBoundInvocationExpressionFromMethodOrPropertyGroup(
syntax As SyntaxNode,
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
diagnostics As DiagnosticBag
) As BoundExpression
Dim boundCall = BindInvocationExpression(syntax, syntax,
TypeCharacter.None,
methodOrPropertyGroup,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
diagnostics,
callerInfoOpt:=syntax)
Return MakeRValue(boundCall, diagnostics)
End Function
''' <summary>
''' Checks if a given symbol is a function that takes no parameters.
''' </summary>
Private Shared ReadOnly s_isFunctionWithoutArguments As Func(Of Symbol, Boolean) = Function(sym)
If sym.Kind = SymbolKind.Method Then
Dim method = DirectCast(sym, MethodSymbol)
Return Not method.IsSub() AndAlso
Not method.IsGenericMethod AndAlso
method.CanBeCalledWithNoParameters
End If
Return False
End Function
''' <summary>
''' Checks if a given symbol is a property that is readable.
''' </summary>
Private Shared ReadOnly s_isReadablePropertyWithoutArguments As Func(Of Symbol, Boolean) = Function(sym)
If sym.Kind = SymbolKind.Property Then
Dim prop = DirectCast(sym, PropertySymbol)
Return prop.IsReadable AndAlso
Not prop.GetMostDerivedGetMethod().IsGenericMethod AndAlso
prop.GetCanBeCalledWithNoParameters
End If
Return False
End Function
''' <summary>
''' Returns the lookup result if at least one found symbol matches the requirements that are verified
''' by using the given symbolChecker. Extension methods will be considered in this check.
''' </summary>
''' <param name="name">The name of the method or property to look for.</param>
''' <param name="container">The container to look in.</param>
''' <param name="symbolChecker">The symbol checker which performs additional checks.</param>
Private Function GetMemberIfMatchesRequirements(
name As String,
container As TypeSymbol,
symbolChecker As Func(Of Symbol, Boolean),
result As LookupResult,
syntax As SyntaxNode,
diagnostics As DiagnosticBag
) As Boolean
result.Clear()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
LookupMember(result, container, name, 0, LookupOptions.AllMethodsOfAnyArity, useSiteDiagnostics)
diagnostics.Add(syntax, useSiteDiagnostics)
useSiteDiagnostics = Nothing
If result.IsGood Then
For Each candidateSymbol In result.Symbols
If symbolChecker(candidateSymbol) Then
Return True
End If
Next
' if there are instance methods in the results, there will be no extension methods.
' Therefore we need to check separately.
If result.Symbols(0).Kind = SymbolKind.Method AndAlso
Not DirectCast(result.Symbols(0), MethodSymbol).IsReducedExtensionMethod Then
result.Clear()
LookupExtensionMethods(result,
container,
name,
0,
LookupOptions.AllMethodsOfAnyArity,
useSiteDiagnostics)
diagnostics.Add(syntax, useSiteDiagnostics)
If result.IsGood Then
For Each candidateSymbol In result.Symbols
If symbolChecker(candidateSymbol) Then
Return True
End If
Next
End If
Debug.Assert(Not result.IsAmbiguous)
End If
ElseIf result.IsAmbiguous Then
' save these diagnostics to report them if the collection does not match the design pattern at all instead of the
' generic diagnostic
Debug.Assert(result.HasDiagnostic)
diagnostics.Clear()
diagnostics.Add(New VBDiagnostic(result.Diagnostic, syntax.GetLocation()))
End If
result.Clear()
Return False
End Function
''' <summary>
''' Determines whether derivedType is, inherits from or implements the given interface.
''' </summary>
''' <param name="derivedType">The possible derived type.</param>
''' <param name="interfaceType">Type of the interface.</param>
''' <param name="useSiteDiagnostics"/>
''' <param name="matchingInterfaces">A list of matching interfaces.</param>
''' <returns>
''' <c>true</c> if derivedType is, inherits from or implements the interface; otherwise, <c>false</c>.
''' </returns>
Friend Shared Function IsOrInheritsFromOrImplementsInterface(
derivedType As TypeSymbol,
interfaceType As NamedTypeSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional matchingInterfaces As HashSet(Of NamedTypeSymbol) = Nothing
) As Boolean
' this is a more specialized version of the Dev10 code for IsOrInheritsFromOrImplements (type_helpers.cpp
' line 1210++) just covering Interfaces.
Debug.Assert(interfaceType.IsDefinition)
If derivedType.IsTypeParameter Then
Dim derivedTypeParameter = DirectCast(derivedType, TypeParameterSymbol)
' check constraints if they have an appropriate relation to the given interface
' if it has a value type constraint, check if system.valuetype satisfies the requirements
If derivedTypeParameter.HasValueTypeConstraint Then
Dim valueTypeSymbol = interfaceType.ContainingAssembly.GetSpecialType(SpecialType.System_ValueType)
If IsOrInheritsFromOrImplementsInterface(valueTypeSymbol, interfaceType, useSiteDiagnostics, matchingInterfaces) AndAlso matchingInterfaces Is Nothing Then
Return True
End If
End If
' check if any interface constraint has the appropriate relation to the base type
For Each typeConstraint In derivedTypeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If IsOrInheritsFromOrImplementsInterface(typeConstraint, interfaceType, useSiteDiagnostics, matchingInterfaces) AndAlso matchingInterfaces Is Nothing Then
Return True
End If
Next
Else
' derivedType could be an interface
If derivedType.OriginalDefinition = interfaceType Then
If matchingInterfaces Is Nothing Then
Return True
End If
matchingInterfaces.Add(DirectCast(derivedType, NamedTypeSymbol))
End If
' implements or inherits interface
For Each interfaceOfDerived In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If interfaceOfDerived.OriginalDefinition = interfaceType Then
If matchingInterfaces Is Nothing Then
Return True
End If
matchingInterfaces.Add(interfaceOfDerived)
End If
Next
End If
Return matchingInterfaces IsNot Nothing AndAlso matchingInterfaces.Count > 0
End Function
Public Function BindWithBlock(node As WithBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim binder As Binder = Me.GetBinder(DirectCast(node, VisualBasicSyntaxNode))
Return Binder.CreateBoundWithBlock(node, binder, diagnostics)
End Function
Protected Overridable Function CreateBoundWithBlock(node As WithBlockSyntax, boundBlockBinder As Binder, diagnostics As DiagnosticBag) As BoundStatement
Return Me.ContainingBinder.CreateBoundWithBlock(node, boundBlockBinder, diagnostics)
End Function
''' <summary>
''' Initially binding using blocks.
''' A Using statement names a resource that is supposed to be disposed on completion.
''' The resource can be an expression or a list of local variables with initializers.
''' the type of the resource must implement System.IDispose
''' A using statement of the form:
''' using Expression
''' list_of_statements
''' end using
'''
''' when the resource is a using locally declared variable no temporary is generated but the variable is read-only
''' A using statement of the form:
''' using v as new myDispose
''' list_of_statements
''' end using
''' It is also possible to use multiple variable resources:
''' using v1 as new myDispose, v2 as myDispose = new myDispose()
''' list_of_statements
''' end using
'''</summary>
Public Function BindUsingBlock(node As UsingBlockSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim usingBinder = Me.GetBinder(node)
Debug.Assert(usingBinder IsNot Nothing)
Dim resourceList As ImmutableArray(Of BoundLocalDeclarationBase) = Nothing
Dim resourceExpression As BoundExpression = Nothing
Dim usingStatement = node.UsingStatement
Dim usingVariableDeclarations = usingStatement.Variables
Dim usingVariableDeclarationCount = usingVariableDeclarations.Count
Dim iDisposable = GetSpecialType(SpecialType.System_IDisposable,
node,
diagnostics)
Dim placeholderInfo = New Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression))()
If usingVariableDeclarationCount > 0 Then
' this is the case of a using statement with one or more variable declarations.
' this will bind the declaration, infer the local's type if needed and binds the initialization expression.
' implicit variable declarations are handled in that method as well (Option Explicit Off)
resourceList = usingBinder.BindVariableDeclarators(usingVariableDeclarations, diagnostics)
' now that the variable declarations and initialization expression are bound, report
' using statement related diagnostics.
For resourceIndex = 0 To usingVariableDeclarationCount - 1
Dim localDeclarations = resourceList(resourceIndex)
Dim declarationSyntax = localDeclarations.Syntax
' bound locals have the identifier syntax as their syntax, but for error messages we want to
' show squiggles under the whole declaration.
' There is one exception to this rule: the parent is a declarator and has multiple names then
' the identifier syntax should be used to be able to distinguish between the error locations.
' e.g. dim x, y as Integer = 23
Dim syntaxNodeForErrors As SyntaxNode
If localDeclarations.Kind <> BoundKind.AsNewLocalDeclarations Then
syntaxNodeForErrors = declarationSyntax.Parent
If syntaxNodeForErrors Is Nothing OrElse
DirectCast(syntaxNodeForErrors, VariableDeclaratorSyntax).Names.Count > 1 Then
syntaxNodeForErrors = declarationSyntax
End If
Else
syntaxNodeForErrors = declarationSyntax
End If
' check if all declared variables are initialized
If localDeclarations.Kind = BoundKind.LocalDeclaration Then
Dim boundLocalDeclaration = DirectCast(localDeclarations, boundLocalDeclaration)
Dim initializerExpression = boundLocalDeclaration.InitializerOpt
If initializerExpression Is Nothing Then
ReportDiagnostic(diagnostics,
syntaxNodeForErrors,
ErrorFactory.ErrorInfo(ERRID.ERR_UsingResourceVarNeedsInitializer))
End If
VerifyUsingVariableDeclarationAndBuildUsingInfo(syntaxNodeForErrors,
boundLocalDeclaration.LocalSymbol,
iDisposable,
placeholderInfo,
diagnostics)
Else
Dim boundAsNewDeclarations = DirectCast(localDeclarations, BoundAsNewLocalDeclarations)
' there can be multiple variables be declared in an "As New"
For declarationIndex = 0 To boundAsNewDeclarations.LocalDeclarations.Length - 1
Dim localDeclaration As BoundLocalDeclaration = boundAsNewDeclarations.LocalDeclarations(declarationIndex)
VerifyUsingVariableDeclarationAndBuildUsingInfo(localDeclaration.Syntax,
localDeclaration.LocalSymbol,
iDisposable,
placeholderInfo,
diagnostics)
Next
End If
Next
Else
' the using block has an expression as resource
Debug.Assert(usingStatement.Expression IsNot Nothing)
Dim resourceExpressionSyntax = usingStatement.Expression
resourceExpression = BindRValue(resourceExpressionSyntax, diagnostics)
Dim resourceExpressionType = resourceExpression.Type
If Not resourceExpressionType.IsErrorType AndAlso Not iDisposable.IsErrorType Then
BuildAndVerifyUsingInfo(resourceExpressionSyntax,
resourceExpression.Type,
placeholderInfo,
iDisposable,
diagnostics)
End If
End If
' Bind the body of the using statement.
Dim usingBody As BoundBlock = BindBlock(node, node.Statements, diagnostics)
Dim usingInfo As New usingInfo(node, placeholderInfo)
Return New BoundUsingStatement(node, resourceList, resourceExpression, usingBody, usingInfo)
End Function
Private Sub VerifyUsingVariableDeclarationAndBuildUsingInfo(
syntaxNode As SyntaxNode,
localSymbol As LocalSymbol,
iDisposable As TypeSymbol,
placeholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression)),
diagnostics As DiagnosticBag
)
Dim declarationType As TypeSymbol = localSymbol.Type
' Explicit array sizes in declarators imply creating an array this is not supported.
' The resource variable type needs to implement System.IDisposable and System.Array is known to not implement it.
If declarationType.IsArrayType Then
' this diagnostic will be reported even if a missing initializer was reported before. This is a change
' from Dev10 which stopped "binding" at the first error
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.ERR_UsingResourceVarCantBeArray))
ElseIf Not declarationType.IsErrorType AndAlso Not iDisposable.IsErrorType Then
BuildAndVerifyUsingInfo(syntaxNode,
declarationType,
placeholderInfo,
iDisposable,
diagnostics)
' TODO: Dev10 shows the error on the symbol name, not the whole declaration. See bug 10720
' TODO: we could suppress this warning if the type does not implement IDisposable and is not late bound.
' BuildAndVerifyUsingInfo would need to return a boolean then, it has all the information available.
ReportMutableStructureConstraintsInUsing(declarationType,
localSymbol.Name,
syntaxNode,
diagnostics)
End If
End Sub
Private Sub BuildAndVerifyUsingInfo(
syntaxNode As SyntaxNode,
resourceType As TypeSymbol,
placeholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression)),
iDisposable As TypeSymbol,
diagnostics As DiagnosticBag
)
If Not placeholderInfo.ContainsKey(resourceType) Then
' TODO: add late binding, see statementsemantics.cpp lines 6765++
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conversionKind = Conversions.ClassifyDirectCastConversion(resourceType, iDisposable, useSiteDiagnostics)
If diagnostics.Add(syntaxNode, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
Dim isValidDispose = Conversions.IsWideningConversion(conversionKind)
If isValidDispose OrElse
(resourceType.IsObjectType() AndAlso OptionStrict <> OptionStrict.On) Then
Dim resourcePlaceholder = New BoundRValuePlaceholder(syntaxNode, resourceType)
Dim disposeConversion As BoundExpression = Nothing
Dim disposeCondition As BoundExpression = Nothing
If Not resourceType.IsValueType Then
disposeConversion = ApplyImplicitConversion(syntaxNode, iDisposable, resourcePlaceholder, diagnostics)
disposeCondition = BindIsExpression(resourcePlaceholder,
New BoundLiteral(syntaxNode, ConstantValue.Nothing, Nothing),
syntaxNode, True, diagnostics)
End If
placeholderInfo.Add(resourceType,
New ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression)(
resourcePlaceholder,
disposeConversion,
disposeCondition))
Else
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.ERR_UsingRequiresDisposePattern, resourceType))
End If
End If
End Sub
''' <summary>Check the given type of and report WRN_MutableGenericStructureInUsing if needed.</summary>
''' <remarks>This function should only be called for a type of a using variable.</remarks>
Private Sub ReportMutableStructureConstraintsInUsing(type As TypeSymbol, symbolName As String, syntaxNode As SyntaxNode, diagnostics As DiagnosticBag)
' Dev10 #666593: Warn if the type of the variable is not a reference type or an immutable structure.
If Not type.IsReferenceType Then
If type.IsTypeParameter Then
If type.IsValueType Then
Dim typeParameter = DirectCast(type, TypeParameterSymbol)
' there is currently no way to only get the type constraint from a type parameter. So we're
' iterating over all of them
Dim processedValueTypes As Boolean = False
For Each constraintType In DirectCast(type, TypeParameterSymbol).ConstraintTypesNoUseSiteDiagnostics
' TODO: if this constraint is a type parameter as well, dig into its constraints as well.
' there is a case where a type constraint of a type parameter is a concrete structure,
' therefore we'll need to check the type constraint as well.
' See TypeParameter.IsValueType for more information
If constraintType.IsValueType Then
processedValueTypes = True
If ShouldReportMutableStructureInUsing(constraintType) Then
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.WRN_MutableStructureInUsing, symbolName))
Return
End If
End If
Next
' only show this message if there was no class constraint which is a value type
' this can be the case of a "Structure" constraint with only interface constraints
If Not processedValueTypes Then
' the type parameter only has a structure constraint
Debug.Assert(typeParameter.HasValueTypeConstraint)
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.WRN_MutableStructureInUsing, symbolName))
End If
Else
' it's just a generic type parameter, show generic diagnostics
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.WRN_MutableGenericStructureInUsing, symbolName))
End If
ElseIf ShouldReportMutableStructureInUsing(type) Then
ReportDiagnostic(diagnostics,
syntaxNode,
ErrorFactory.ErrorInfo(ERRID.WRN_MutableStructureInUsing, symbolName))
End If
End If
End Sub
' This method decides if a WRN_MutableStructureInUsing should be shown for a given type of the Using variable.
' The purpose of this function is to avoid code duplication in 'CheckForMutableStructureConstraints'.
' This is not a general purpose helper.
Private Shared Function ShouldReportMutableStructureInUsing(structureType As TypeSymbol) As Boolean
Debug.Assert(structureType.IsValueType)
If structureType.Kind = SymbolKind.NamedType Then
If structureType.IsStructureType AndAlso Not structureType.IsEnumType AndAlso Not structureType.IsIntrinsicType Then
For Each member In structureType.GetMembersUnordered
If member.Kind = SymbolKind.Field AndAlso
Not member.IsShared AndAlso Not DirectCast(member, FieldSymbol).IsReadOnly Then
Return True
End If
Next
Else
Debug.Assert(Not structureType.IsVoidType)
End If
End If
Return False
End Function
''' <summary>
''' Binds a sync lock block.
''' A SyncLock come in the following form:
'''
''' SyncLock <expression>
''' <body>
''' End SyncLock
''' </summary>
''' <param name="node">The node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Public Function BindSyncLockBlock(node As SyncLockBlockSyntax, diagnostics As DiagnosticBag) As BoundSyncLockStatement
' bind the expression
Dim lockExpression As BoundExpression = BindRValue(node.SyncLockStatement.Expression, diagnostics)
Dim lockExpressionType = lockExpression.Type
If Not lockExpression.HasErrors Then
If Not lockExpressionType.IsReferenceType Then
ReportDiagnostic(diagnostics,
lockExpression.Syntax,
ErrorFactory.ErrorInfo(ERRID.ERR_SyncLockRequiresReferenceType1, lockExpressionType))
End If
End If
Dim boundBody = BindBlock(node, node.Statements, diagnostics)
Return New BoundSyncLockStatement(node, lockExpression, boundBody)
End Function
Public Function BindTryBlock(node As TryBlockSyntax, diagnostics As DiagnosticBag) As BoundTryStatement
Debug.Assert(node IsNot Nothing)
Dim tryBlock As BoundBlock = BindBlock(node, node.Statements, diagnostics)
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = BindCatchBlocks(node.CatchBlocks, diagnostics)
Dim finallyBlockOpt As BoundBlock
If node.FinallyBlock IsNot Nothing Then
Dim finallyBinder = GetBinder(node.FinallyBlock)
finallyBlockOpt = finallyBinder.BindBlock(node.FinallyBlock, node.FinallyBlock.Statements, diagnostics)
Else
finallyBlockOpt = Nothing
End If
If catchBlocks.IsEmpty AndAlso finallyBlockOpt Is Nothing Then
ReportDiagnostic(diagnostics, node.TryStatement, ERRID.ERR_TryWithoutCatchOrFinally)
End If
Dim tryBinder As Binder = GetBinder(node)
Return New BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt, tryBinder.GetExitLabel(SyntaxKind.ExitTryStatement))
End Function
Public Function BindCatchBlocks(catchClauses As SyntaxList(Of CatchBlockSyntax), diagnostics As DiagnosticBag) As ImmutableArray(Of BoundCatchBlock)
Dim n As Integer = catchClauses.Count
If n = 0 Then
Return ImmutableArray(Of BoundCatchBlock).Empty
End If
Dim catchBlocks = ArrayBuilder(Of BoundCatchBlock).GetInstance(n)
For Each catchSyntax In catchClauses
Dim catchBinder As Binder = GetBinder(catchSyntax)
Dim catchBlock As BoundCatchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics)
catchBlocks.Add(catchBlock)
Next
Return catchBlocks.ToImmutableAndFree
End Function
Private Function BindCatchBlock(node As CatchBlockSyntax, previousBlocks As ArrayBuilder(Of BoundCatchBlock), diagnostics As DiagnosticBag) As BoundCatchBlock
' we need to compute the following parts
Dim catchLocal As LocalSymbol = Nothing
Dim exceptionSource As BoundExpression = Nothing
Dim exceptionFilter As BoundExpression = Nothing
Dim exceptionType As TypeSymbol
Dim hasError = False
Dim declaration = node.CatchStatement
Dim name As IdentifierNameSyntax = declaration.IdentifierName
Dim asClauseOpt = declaration.AsClause
' if we have "as" we need to declare a local
If asClauseOpt IsNot Nothing Then
Dim localAccess As BoundLocal = BindCatchVariableDeclaration(name, asClauseOpt, diagnostics)
exceptionSource = localAccess
catchLocal = localAccess.LocalSymbol
ElseIf name IsNot Nothing Then
exceptionSource = BindSimpleName(name, False, diagnostics)
End If
' verify the catch variable.
' 1) must be a local or parameter (byref parameters are ok, static locals are not).
' 2) must be or derive from System.Exception
If exceptionSource IsNot Nothing Then
Dim originalExceptionValue As BoundExpression = exceptionSource
If Not exceptionSource.IsValue OrElse exceptionSource.Type Is Nothing OrElse exceptionSource.Type.IsVoidType Then
exceptionSource = BadExpression(exceptionSource.Syntax, exceptionSource, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
End If
exceptionType = exceptionSource.Type
If originalExceptionValue.HasErrors Then
hasError = True
Else
Dim exprKind = exceptionSource.Kind
If Not (exprKind = BoundKind.Parameter OrElse
exprKind = BoundKind.Local AndAlso Not DirectCast(exceptionSource, BoundLocal).LocalSymbol.IsStatic) Then
ReportDiagnostic(diagnostics, name, ERRID.ERR_CatchVariableNotLocal1, name.ToString())
hasError = True
Else
' type of the catch variable must derive from Exception
Debug.Assert(exceptionType IsNot Nothing)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If exceptionType.IsErrorType() Then
hasError = True
ElseIf Not exceptionType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Exception, Compilation, useSiteDiagnostics) Then
ReportDiagnostic(diagnostics,
If(asClauseOpt IsNot Nothing, asClauseOpt.Type, name),
ERRID.ERR_CatchNotException1,
exceptionType)
hasError = True
diagnostics.Add(If(asClauseOpt IsNot Nothing, asClauseOpt.Type, name), useSiteDiagnostics)
End If
End If
End If
Else
exceptionType = GetWellKnownType(WellKnownType.System_Exception, node, diagnostics)
End If
Dim whenSyntax = declaration.WhenClause
If whenSyntax IsNot Nothing Then
exceptionFilter = BindBooleanExpression(whenSyntax.Filter, diagnostics)
End If
If Not hasError Then
Debug.Assert(exceptionType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Exception, Compilation, Nothing))
For Each previousBlock In previousBlocks
If previousBlock.ExceptionFilterOpt IsNot Nothing Then
' filters are considered to have behavior defined at run time
' therefore catches with filters are not considered in this analysis
' the fact that filter may be a compile-time constant is ignored.
Continue For
End If
Dim previousType As TypeSymbol
If previousBlock.ExceptionSourceOpt IsNot Nothing Then
previousType = previousBlock.ExceptionSourceOpt.Type
Else
' do not report diagnostics if type is missing, it should have been already recorded.
previousType = Compilation.GetWellKnownType(WellKnownType.System_Exception)
End If
If Not previousType.IsErrorType() Then
If previousType = exceptionType Then
ReportDiagnostic(diagnostics, declaration, ERRID.WRN_DuplicateCatch, exceptionType)
Exit For
End If
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim isBaseType As Boolean = exceptionType.IsOrDerivedFrom(previousType, useSiteDiagnostics)
diagnostics.Add(declaration, useSiteDiagnostics)
If isBaseType Then
ReportDiagnostic(diagnostics, declaration, ERRID.WRN_OverlappingCatch, exceptionType, previousType)
Exit For
End If
End If
Next
End If
Dim block = Me.BindBlock(node, node.Statements, diagnostics)
Return New BoundCatchBlock(node, catchLocal, exceptionSource,
errorLineNumberOpt:=Nothing,
exceptionFilterOpt:=exceptionFilter,
body:=block,
hasErrors:=hasError,
isSynthesizedAsyncCatchAll:=False)
End Function
Private Function BindExitStatement(node As ExitStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim targetLabel As LabelSymbol = GetExitLabel(node.Kind)
If targetLabel Is Nothing Then
Dim id As ERRID
Select Case node.Kind
Case SyntaxKind.ExitWhileStatement : id = ERRID.ERR_ExitWhileNotWithinWhile
Case SyntaxKind.ExitTryStatement : id = ERRID.ERR_ExitTryNotWithinTry
Case SyntaxKind.ExitDoStatement : id = ERRID.ERR_ExitDoNotWithinDo
Case SyntaxKind.ExitForStatement : id = ERRID.ERR_ExitForNotWithinFor
Case SyntaxKind.ExitSelectStatement : id = ERRID.ERR_ExitSelectNotWithinSelect
Case SyntaxKind.ExitSubStatement : id = ERRID.ERR_ExitSubOfFunc
Case SyntaxKind.ExitFunctionStatement : id = ERRID.ERR_ExitFuncOfSub
Case SyntaxKind.ExitPropertyStatement : id = ERRID.ERR_ExitPropNot
Case Else : ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
ReportDiagnostic(diagnostics, node, id)
Return New BoundBadStatement(node, ImmutableArray(Of BoundNode).Empty, hasErrors:=True)
Else
Return New BoundExitStatement(node, targetLabel)
End If
End Function
Private Function BindContinueStatement(node As ContinueStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim targetLabel As LabelSymbol = GetContinueLabel(node.Kind)
If targetLabel Is Nothing Then
Dim id As ERRID
Select Case node.Kind
Case SyntaxKind.ContinueWhileStatement : id = ERRID.ERR_ContinueWhileNotWithinWhile
Case SyntaxKind.ContinueDoStatement : id = ERRID.ERR_ContinueDoNotWithinDo
Case SyntaxKind.ContinueForStatement : id = ERRID.ERR_ContinueForNotWithinFor
Case Else : ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
ReportDiagnostic(diagnostics, node, id)
Return New BoundBadStatement(node, ImmutableArray(Of BoundNode).Empty, hasErrors:=True)
Else
Return New BoundContinueStatement(node, targetLabel)
End If
End Function
Private Function BindBooleanExpression(node As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' 11.19 Boolean Expressions
Dim expr As BoundExpression = Me.BindValue(node, diagnostics, isOperandOfConditionalBranch:=True)
Dim boolSymbol As NamedTypeSymbol = GetSpecialType(SpecialType.System_Boolean, node, diagnostics)
' NOTE: Errors in 'expr' will be handles properly by ApplyImplicitConversion(...)
Return Me.ApplyImplicitConversion(node, boolSymbol, expr, diagnostics, isOperandOfConditionalBranch:=True)
End Function
Private Function GetCurrentReturnType(<Out()> ByRef isAsync As Boolean,
<Out()> ByRef isIterator As Boolean,
<Out()> ByRef methodReturnType As TypeSymbol) As TypeSymbol
isAsync = False
isIterator = False
Dim method As MethodSymbol = TryCast(Me.ContainingMember, MethodSymbol)
If method IsNot Nothing Then
methodReturnType = method.ReturnType
isAsync = method.IsAsync
' method cannot be both iterator and async, so async will win here.
isIterator = Not isAsync AndAlso method.IsIterator
If Not method.IsSub Then
If isAsync AndAlso method.ReturnType.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) Then
Return DirectCast(method.ReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
ElseIf isAsync AndAlso method.ReturnType.Equals(Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) Then
' I don't believe we need to report use-site error here because we are using System.Void just as an indicator that we don't expect any value to be returned.
Return Compilation.GetSpecialType(SpecialType.System_Void)
ElseIf isIterator Then
' I don't believe we need to report use-site error here because we are using System.Void just as an indicator that we don't expect any value to be returned.
Return Compilation.GetSpecialType(SpecialType.System_Void)
End If
End If
Return methodReturnType
End If
methodReturnType = ErrorTypeSymbol.UnknownResultType
Return methodReturnType
End Function
Private Function BindReturn(originalSyntax As ReturnStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim expressionSyntax As expressionSyntax = originalSyntax.Expression
' UNDONE - Handle ERRID_ReturnFromEventMethod
' If we are in a lambda binding, then the original syntax could be just the expression.
' If we are not in a lambda binding then we have a real return statement.
Debug.Assert(originalSyntax IsNot Nothing)
Debug.Assert(expressionSyntax Is originalSyntax OrElse originalSyntax.Expression Is expressionSyntax)
Dim isAsync As Boolean
Dim isIterator As Boolean
Dim methodReturnType As TypeSymbol = Nothing
Dim retType As TypeSymbol = Me.GetCurrentReturnType(isAsync, isIterator, methodReturnType)
Dim returnLabel = GetReturnLabel()
If BindingTopLevelScriptCode Then
ReportDiagnostic(diagnostics, originalSyntax, ERRID.ERR_KeywordNotAllowedInScript, SyntaxFacts.GetText(SyntaxKind.ReturnKeyword))
Return New BoundReturnStatement(originalSyntax, Nothing, Nothing, returnLabel, hasErrors:=True)
End If
If retType.SpecialType = SpecialType.System_Void Then
' For subs just generate a return
If expressionSyntax IsNot Nothing Then
ReportDiagnostic(diagnostics, originalSyntax,
If(isIterator,
ERRID.ERR_BadReturnValueInIterator,
If(isAsync AndAlso Not methodReturnType.SpecialType = SpecialType.System_Void, ERRID.ERR_ReturnFromNonGenericTaskAsync, ERRID.ERR_ReturnFromNonFunction)))
Dim arg As BoundExpression = Me.BindValue(expressionSyntax, diagnostics)
arg = MakeRValueAndIgnoreDiagnostics(arg)
Return New BoundReturnStatement(originalSyntax, arg, Nothing, returnLabel, hasErrors:=True)
End If
Return New BoundReturnStatement(originalSyntax, Nothing, Nothing, returnLabel)
Else
Dim arg As BoundExpression = Nothing
If expressionSyntax IsNot Nothing Then
arg = Me.BindValue(expressionSyntax, diagnostics)
End If
If arg IsNot Nothing Then
If retType Is LambdaSymbol.ReturnTypeIsUnknown Then
' We will have LambdaSymbol.ReturnTypeIsUnknown as the target return type
' if we are inside a lambda, for which we failed to infer the return type.
Debug.Assert(Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.LambdaMethod)
' We want to make sure that the return expressions are as bound as they can be.
' For example, if return expression is a lambda, we want it to be a BoundLambda, not
' an UnboundLambda node (that is what BindValue stops at). In order to get to BoundLambda,
' we need to call MakeRValue, but we will ignore any diagnostics it will produce because
' an inference error has been reported earlier.
arg = MakeRValueAndIgnoreDiagnostics(arg)
ElseIf retType Is LambdaSymbol.ReturnTypeIsBeingInferred Then
' Target retType can be LambdaSymbol.ReturnTypeIsBeingInferred if we are inferring return type of a lambda.
' We should leave expression unmodified, to allow more accurate inference.
Debug.Assert(Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.LambdaMethod)
Else
' If we were in an async method that returned Task<T> for some T,
' and the return expression can't be converted to T but is identical to Task<T>,
' then don't give the normal error message about "there is no conversion from T to Task<T>"
' and instead say "Since this is async, the return expression must be 'T' rather than 'Task<T>'."
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If isAsync AndAlso Not retType.IsErrorType() AndAlso methodReturnType.Equals(arg.Type) AndAlso
methodReturnType.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) AndAlso
Not Conversions.ConversionExists(Conversions.ClassifyConversion(arg, retType, Me, useSiteDiagnostics).Key) Then
If Not diagnostics.Add(arg, useSiteDiagnostics) Then
ReportDiagnostic(diagnostics, arg.Syntax, ERRID.ERR_BadAsyncReturnOperand1, retType)
End If
arg = MakeRValueAndIgnoreDiagnostics(arg)
Else
arg = ApplyImplicitConversion(arg.Syntax, retType, arg, diagnostics)
End If
End If
End If
' For functions generate return expression with local return value symbol
If arg IsNot Nothing Then
Return New BoundReturnStatement(originalSyntax, arg, GetLocalForFunctionValue(), returnLabel)
Else
If isAsync AndAlso retType Is LambdaSymbol.ReturnTypeIsBeingInferred Then
' Target retType can be LambdaSymbol.ReturnTypeIsBeingInferred if we are inferring return type of a lambda.
' We should not require expression, to allow more accurate inference.
Debug.Assert(Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.LambdaMethod)
Return New BoundReturnStatement(originalSyntax, Nothing, Nothing, returnLabel, hasErrors:=False)
Else
ReportDiagnostic(diagnostics, originalSyntax, ERRID.ERR_ReturnWithoutValue)
Return New BoundReturnStatement(originalSyntax, Nothing, Nothing, returnLabel, hasErrors:=True)
End If
End If
End If
End Function
Private Function GetCurrentYieldType(node As YieldStatementSyntax,
diagnostics As DiagnosticBag) As TypeSymbol
Dim method As MethodSymbol = TryCast(Me.ContainingMember, MethodSymbol)
If method IsNot Nothing Then
Dim methodReturnType = method.ReturnType
If Not method.IsIterator Then
' no idea how we can get here since parsing of Yield is contextual, but there is an error ID for this
ReportDiagnostic(diagnostics, node, ERRID.ERR_BadYieldInNonIteratorMethod)
End If
If Not method.IsSub Then
Dim returnNamedType = TryCast(methodReturnType.OriginalDefinition, NamedTypeSymbol)
Dim returnSpecialType As SpecialType = If(returnNamedType IsNot Nothing, returnNamedType.SpecialType, Nothing)
If returnSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T OrElse
returnSpecialType = SpecialType.System_Collections_Generic_IEnumerator_T Then
Return DirectCast(methodReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
End If
If returnSpecialType = SpecialType.System_Collections_IEnumerable OrElse
returnSpecialType = SpecialType.System_Collections_IEnumerator Then
Return GetSpecialType(SpecialType.System_Object, node, diagnostics)
End If
End If
If methodReturnType Is LambdaSymbol.ReturnTypeIsUnknown OrElse
methodReturnType Is LambdaSymbol.ReturnTypeIsBeingInferred Then
Return methodReturnType
End If
End If
' It is either nongeneric iterator or an error (which should be already reported).
Return ErrorTypeSymbol.UnknownResultType
End Function
Private Function BindYield(originalSyntax As YieldStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim expressionSyntax As expressionSyntax = originalSyntax.Expression
Dim arg As BoundExpression = Me.BindValue(expressionSyntax, diagnostics)
If BindingTopLevelScriptCode Then
ReportDiagnostic(diagnostics, originalSyntax, ERRID.ERR_KeywordNotAllowedInScript, SyntaxFacts.GetText(SyntaxKind.YieldKeyword))
arg = MakeRValueAndIgnoreDiagnostics(arg)
Return New BoundYieldStatement(originalSyntax, arg, hasErrors:=True)
End If
Dim retType As TypeSymbol = Me.GetCurrentYieldType(originalSyntax, diagnostics)
If retType Is LambdaSymbol.ReturnTypeIsUnknown Then
' We will have LambdaSymbol.ReturnTypeIsUnknown as the target return type
' if we are inside a lambda, for which we failed to infer the return type.
Debug.Assert(Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.LambdaMethod)
' We want to make sure that the return expressions are as bound as they can be.
' For example, if return expression is a lambda, we want it to be a BoundLambda, not
' an UnboundLambda node (that is what BindValue stops at). In order to get to BoundLambda,
' we need to call MakeRValue, but we will ignore any diagnostics it will produce because
' an inference error has been reported earlier.
arg = MakeRValueAndIgnoreDiagnostics(arg)
ElseIf retType Is LambdaSymbol.ReturnTypeIsBeingInferred Then
' Target retType can be LambdaSymbol.ReturnTypeIsBeingInferred if we are inferring return type of a lambda.
' We should leave expression unmodified, to allow more accurate inference.
Debug.Assert(Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.LambdaMethod)
Return New BoundYieldStatement(originalSyntax, arg, hasErrors:=False, returnTypeIsBeingInferred:=True)
Else
arg = ApplyImplicitConversion(arg.Syntax, retType, arg, diagnostics)
End If
Return New BoundYieldStatement(originalSyntax, arg)
End Function
Private Function BindThrow(node As ThrowStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim expressionSyntax As expressionSyntax = node.Expression
Dim hasError As Boolean = False
If expressionSyntax Is Nothing Then
Dim curSyntax As VisualBasicSyntaxNode = node.Parent
Dim canRethrow As Boolean = False
While curSyntax IsNot Nothing
Select Case curSyntax.Kind
Case SyntaxKind.CatchBlock
canRethrow = True
Exit While
Case SyntaxKind.FinallyBlock
' CLI spec (with Microsoft specific implementation notes).
' 12.4.2.8.2.2 rethrow:
' The Microsoft implementation requires that either the catch handler is the innermost enclosing
' exception-handling block, or all intervening exception-handling blocks are protected regions.
Exit While
Case SyntaxKind.SingleLineFunctionLambdaExpression
Case SyntaxKind.MultiLineFunctionLambdaExpression
Case SyntaxKind.SingleLineSubLambdaExpression
Case SyntaxKind.MultiLineSubLambdaExpression
Exit While
Case Else
If TypeOf curSyntax Is MethodBlockBaseSyntax Then
Exit While
End If
End Select
curSyntax = curSyntax.Parent
End While
If Not canRethrow Then
hasError = True
ReportDiagnostic(diagnostics, node, ERRID.ERR_MustBeInCatchToRethrow)
End If
Return New BoundThrowStatement(node, Nothing, hasError)
Else
Dim value As BoundExpression = BindRValue(expressionSyntax, diagnostics)
Dim exceptionType = value.Type
If Not exceptionType.IsErrorType Then
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not exceptionType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Exception, Compilation, useSiteDiagnostics) Then
hasError = True
ReportDiagnostic(diagnostics, node, ERRID.ERR_CantThrowNonException, exceptionType)
diagnostics.Add(node, useSiteDiagnostics)
End If
Else
hasError = True
End If
Return New BoundThrowStatement(node, value, hasError)
End If
End Function
Private Function BindError(node As ErrorStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
Dim value As BoundExpression = ApplyImplicitConversion(node.ErrorNumber,
GetSpecialType(SpecialType.System_Int32, node.ErrorNumber, diagnostics),
BindValue(node.ErrorNumber, diagnostics),
diagnostics)
Return New BoundThrowStatement(node, value)
End Function
Private Function BindResumeStatement(node As ResumeStatementSyntax, diagnostics As DiagnosticBag) As BoundResumeStatement
If IsInLambda Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_MultilineLambdasCannotContainOnError)
ElseIf IsInAsyncContext() OrElse IsInIteratorContext() Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_ResumablesCannotContainOnError)
End If
Select Case node.Kind
Case SyntaxKind.ResumeStatement
Return New BoundResumeStatement(node)
Case SyntaxKind.ResumeNextStatement
Return New BoundResumeStatement(node, isNext:=True)
Case SyntaxKind.ResumeLabelStatement
Dim symbol As LabelSymbol = Nothing
Dim boundLabelExpression As BoundExpression = BindExpression(node.Label, diagnostics)
If boundLabelExpression.Kind = BoundKind.Label Then
Dim boundLabel = DirectCast(boundLabelExpression, boundLabel)
symbol = boundLabel.Label
Return New BoundResumeStatement(node, symbol, boundLabel, hasErrors:=Not IsValidLabelForGoto(symbol, node.Label, diagnostics))
Else
' if the bound label is e.g. a bad bound expression because of a non-existent label,
' make this a bad statement.
Return New BoundResumeStatement(node, Nothing, boundLabelExpression, hasErrors:=True)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
Private Function BindOnErrorStatement(node As StatementSyntax, diagnostics As DiagnosticBag) As BoundOnErrorStatement
If IsInLambda Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_MultilineLambdasCannotContainOnError)
ElseIf IsInAsyncContext() OrElse IsInIteratorContext() Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_ResumablesCannotContainOnError)
End If
Select Case node.Kind
Case SyntaxKind.OnErrorGoToMinusOneStatement
Return New BoundOnErrorStatement(node, OnErrorStatementKind.GoToMinusOne, Nothing, Nothing)
Case SyntaxKind.OnErrorGoToZeroStatement
Return New BoundOnErrorStatement(node, OnErrorStatementKind.GoToZero, Nothing, Nothing)
Case SyntaxKind.OnErrorResumeNextStatement
Return New BoundOnErrorStatement(node, OnErrorStatementKind.ResumeNext, Nothing, Nothing)
Case SyntaxKind.OnErrorGoToLabelStatement
Dim onError = DirectCast(node, OnErrorGoToStatementSyntax)
Dim symbol As LabelSymbol = Nothing
Dim boundLabelExpression As BoundExpression = BindExpression(onError.Label, diagnostics)
If boundLabelExpression.Kind = BoundKind.Label Then
Dim boundLabel = DirectCast(boundLabelExpression, boundLabel)
symbol = boundLabel.Label
Return New BoundOnErrorStatement(node, symbol, boundLabel, hasErrors:=Not IsValidLabelForGoto(symbol, onError.Label, diagnostics))
Else
' if the bound label is e.g. a bad bound expression because of a non-existent label,
' make this a bad statement.
Return New BoundOnErrorStatement(node, Nothing, boundLabelExpression, hasErrors:=True)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
Private Function BindStopStatement(stopStatementSyntax As StopOrEndStatementSyntax) As BoundStatement
Return New BoundStopStatement(stopStatementSyntax)
End Function
Private Function BindEndStatement(endStatementSyntax As StopOrEndStatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
If Not Compilation.Options.OutputKind.IsApplication() Then
ReportDiagnostic(diagnostics, endStatementSyntax, ERRID.ERR_EndDisallowedInDllProjects)
End If
Return New BoundEndStatement(endStatementSyntax)
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Statements.vb
|
Visual Basic
|
apache-2.0
| 289,705
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Editor.Implementation.Classification
Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.UnitTests
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Classification
Imports Microsoft.VisualStudio.Text.Tagging
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
<[UseExportProvider]>
Public Class ClassificationTests
<WpfFact, WorkItem(13753, "https://github.com/dotnet/roslyn/issues/13753")>
Public Async Function TestSemanticClassificationWithoutSyntaxTree() As Task
Dim workspaceDefinition =
<Workspace>
<Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true">
<Document>
var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations
</Document>
</Project>
</Workspace>
Dim composition = EditorTestCompositions.EditorFeatures.AddParts(
GetType(NoCompilationContentTypeDefinitions),
GetType(NoCompilationContentTypeLanguageService),
GetType(NoCompilationEditorClassificationService))
Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition)
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Dim provider = New SemanticClassificationViewTaggerProvider(
workspace.GetService(Of IThreadingContext),
workspace.GetService(Of ClassificationTypeMap),
workspace.GetService(Of IGlobalOptionService),
listenerProvider)
Dim buffer = workspace.Documents.First().GetTextBuffer()
Dim tagger = provider.CreateTagger(Of IClassificationTag)(
workspace.Documents.First().GetTextView(),
buffer)
Using edit = buffer.CreateEdit()
edit.Insert(0, " ")
edit.Apply()
End Using
Using DirectCast(tagger, IDisposable)
Await listenerProvider.GetWaiter(FeatureAttribute.Classification).ExpeditedWaitAsync()
' Note: we don't actually care what results we get back. We're just
' verifying that we don't crash because the SemanticViewTagger ends up
' calling SyntaxTree/SemanticModel code.
tagger.GetTags(New NormalizedSnapshotSpanCollection(
New SnapshotSpan(buffer.CurrentSnapshot, New Span(0, 1))))
End Using
End Using
End Function
<WpfFact>
Public Sub TestFailOverOfMissingClassificationType()
Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider()
Dim typeMap = exportProvider.GetExportedValue(Of ClassificationTypeMap)
Dim formatMap = exportProvider.GetExportedValue(Of IClassificationFormatMapService).GetClassificationFormatMap("tooltip")
Dim classifiedText = New ClassifiedText("UnknownClassificationType", "dummy")
Dim run = classifiedText.ToRun(formatMap, typeMap)
Assert.NotNull(run)
End Sub
<WpfFact, WorkItem(13753, "https://github.com/dotnet/roslyn/issues/13753")>
Public Async Function TestWrongDocument() As Task
Dim workspaceDefinition =
<Workspace>
<Project Language="NoCompilation" AssemblyName="NoCompilationAssembly" CommonReferencesPortable="true">
<Document>
var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferencesPortable="true">
</Project>
</Workspace>
Dim composition = EditorTestCompositions.EditorFeatures.AddParts(
GetType(NoCompilationContentTypeLanguageService),
GetType(NoCompilationContentTypeDefinitions))
Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition)
Dim project = workspace.CurrentSolution.Projects.First(Function(p) p.Language = LanguageNames.CSharp)
Dim classificationService = project.LanguageServices.GetService(Of IClassificationService)()
Dim wrongDocument = workspace.CurrentSolution.Projects.First(Function(p) p.Language = "NoCompilation").Documents.First()
Dim text = Await wrongDocument.GetTextAsync(CancellationToken.None)
' make sure we don't crash with wrong document
Dim result = New ArrayBuilder(Of ClassifiedSpan)()
Await classificationService.AddSyntacticClassificationsAsync(wrongDocument, New TextSpan(0, text.Length), result, CancellationToken.None)
Await classificationService.AddSemanticClassificationsAsync(wrongDocument, New TextSpan(0, text.Length), options:=Nothing, result, CancellationToken.None)
End Using
End Function
<ExportLanguageService(GetType(IClassificationService), NoCompilationConstants.LanguageName, ServiceLayer.Test), [Shared], PartNotDiscoverable>
Private Class NoCompilationEditorClassificationService
Implements IClassificationService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Implements IClassificationService.AddLexicalClassifications
End Sub
Public Sub AddSyntacticClassifications(workspace As Workspace, root As SyntaxNode, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Implements IClassificationService.AddSyntacticClassifications
End Sub
Public Function AddSemanticClassificationsAsync(document As Document, textSpan As TextSpan, options As ClassificationOptions, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) As Task Implements IClassificationService.AddSemanticClassificationsAsync
Return Task.CompletedTask
End Function
Public Function AddSyntacticClassificationsAsync(document As Document, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) As Task Implements IClassificationService.AddSyntacticClassificationsAsync
Return Task.CompletedTask
End Function
Public Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan Implements IClassificationService.AdjustStaleClassification
End Function
Public Function ComputeSyntacticChangeRangeAsync(oldDocument As Document, newDocument As Document, timeout As TimeSpan, cancellationToken As CancellationToken) As ValueTask(Of TextChangeRange?) Implements IClassificationService.ComputeSyntacticChangeRangeAsync
Return New ValueTask(Of TextChangeRange?)
End Function
Public Function ComputeSyntacticChangeRange(workspace As Workspace, oldRoot As SyntaxNode, newRoot As SyntaxNode, timeout As TimeSpan, cancellationToken As CancellationToken) As TextChangeRange? Implements IClassificationService.ComputeSyntacticChangeRange
Return Nothing
End Function
Public Function AddEmbeddedLanguageClassificationsAsync(document As Document, textSpan As TextSpan, options As ClassificationOptions, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) As Task Implements IClassificationService.AddEmbeddedLanguageClassificationsAsync
Return Task.CompletedTask
End Function
End Class
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/Test2/Classification/ClassificationTests.vb
|
Visual Basic
|
mit
| 8,998
|
Imports System.IO
Imports System.Collections.Generic
Imports System.IO.MemoryMappedFiles
Imports System.Threading
Imports System.Net
Public Class SharedMemory
'This was originally written with .NET's MemoryMapped File Service and a mutex, and it caused a few problems, so I updated it with this method until the need arises to move this to shared memory.
Private _name As String
Private _mmfpath As String
Public Function GetGridPath(ByVal sType As String) As String
Dim sTemp As String
sTemp = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\gridcoinresearch\" + sType
If System.IO.Directory.Exists(sTemp) = False Then
Try
System.IO.Directory.CreateDirectory(sTemp)
Catch ex As Exception
End Try
End If
Return sTemp
End Function
Public Sub New(name As String)
_name = name
_mmfpath = GetGridPath("database") + "\" + _name
Write("")
End Sub
Public Sub Write(data As String)
Try
Dim fs As New StreamWriter(_mmfpath)
fs.Write(data)
fs.Close()
Catch ex As Exception
End Try
End Sub
Public Function Read() As String
Try
Dim fs As New StreamReader(_mmfpath)
Dim sOut As String
sOut = fs.ReadToEnd()
fs.Close()
Return sOut
Catch ex As Exception
Return ""
End Try
Return ""
End Function
End Class
|
fooforever/Gridcoin-Research
|
contrib/Installer/boinc/boinc/Mutex.vb
|
Visual Basic
|
mit
| 1,544
|
' 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.Globalization
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
<ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.ReduceTokens, LanguageNames.VisualBasic), [Shared]>
<ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.AddMissingTokens, Before:=PredefinedCodeCleanupProviderNames.Format)>
Friend Class ReduceTokensCodeCleanupProvider
Inherits AbstractTokensCodeCleanupProvider
Public Overrides ReadOnly Property Name As String
Get
Return PredefinedCodeCleanupProviderNames.ReduceTokens
End Get
End Property
Protected Overrides Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter)
Return Task.FromResult(Of Rewriter)(New ReduceTokensRewriter(spans, cancellationToken))
End Function
Private Class ReduceTokensRewriter
Inherits AbstractTokensCodeCleanupProvider.Rewriter
Public Sub New(spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken)
MyBase.New(spans, cancellationToken)
End Sub
Public Overrides Function VisitLiteralExpression(node As LiteralExpressionSyntax) As SyntaxNode
Dim newNode = DirectCast(MyBase.VisitLiteralExpression(node), LiteralExpressionSyntax)
Dim literal As SyntaxToken = newNode.Token
' Pretty list floating and decimal literals.
Select Case literal.Kind
Case SyntaxKind.FloatingLiteralToken
' Get the literal identifier text which needs to be pretty listed.
Dim idText = literal.GetIdentifierText()
' Compiler has parsed the literal text as single/double value, fetch the string representation of this value.
Dim value As Double = 0
Dim valueText As String = GetFloatLiteralValueString(literal, value) + GetTypeCharString(literal.GetTypeCharacter())
If value = 0 Then
' Overflow/underflow case or zero literal, skip pretty listing.
Return newNode
End If
' If the string representation of the value differs from the identifier text, create a new literal token with same value but pretty listed "valueText".
If Not CaseInsensitiveComparison.Equals(valueText, idText) Then
Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value))
End If
Case SyntaxKind.DecimalLiteralToken
' Get the literal identifier text which needs to be pretty listed.
Dim idText = literal.GetIdentifierText()
Dim value = DirectCast(literal.Value, Decimal)
If value = 0 Then
' Overflow/underflow case or zero literal, skip pretty listing.
Return newNode
End If
' Compiler has parsed the literal text as a decimal value, fetch the string representation of this value.
Dim valueText As String = GetDecimalLiteralValueString(value) + GetTypeCharString(literal.GetTypeCharacter())
If Not CaseInsensitiveComparison.Equals(valueText, idText) Then
Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value))
End If
Case SyntaxKind.IntegerLiteralToken
' Get the literal identifier text which needs to be pretty listed.
Dim idText = literal.GetIdentifierText()
'The value will only ever be negative when we have a hex or oct value
'it's safe to cast to ULong as we check for negative values later
Dim value As ULong = CType(literal.Value, ULong)
If value = 0 AndAlso HasOverflow(literal.GetDiagnostics()) Then
'Overflow/underflow, skip pretty listing.
Return newNode
End If
Dim base = literal.GetBase()
Const digitSeparator = "_"c
If Not base.HasValue OrElse idText.Contains(digitSeparator) Then
Return newNode
End If
'fetch the string representation of this value in the correct base.
Dim valueText As String = GetIntegerLiteralValueString(literal.Value, base.Value) + GetTypeCharString(literal.GetTypeCharacter())
If Not CaseInsensitiveComparison.Equals(valueText, idText) Then
Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value))
End If
End Select
Return newNode
End Function
Private Shared Function GetTypeCharString(typeChar As TypeCharacter) As String
Select Case typeChar
Case TypeCharacter.Single
Return "!"
Case TypeCharacter.SingleLiteral
Return "F"
Case TypeCharacter.Double
Return "#"
Case TypeCharacter.DoubleLiteral
Return "R"
Case TypeCharacter.Decimal
Return "@"
Case TypeCharacter.DecimalLiteral
Return "D"
Case TypeCharacter.Integer
Return "%"
Case TypeCharacter.IntegerLiteral
Return "I"
Case TypeCharacter.ShortLiteral
Return "S"
Case TypeCharacter.Long
Return "&"
Case TypeCharacter.LongLiteral
Return "L"
Case TypeCharacter.UIntegerLiteral
Return "UI"
Case TypeCharacter.UShortLiteral
Return "US"
Case TypeCharacter.ULongLiteral
Return "UL"
Case Else
Return ""
End Select
End Function
Private Shared Function GetFloatLiteralValueString(literal As SyntaxToken, <Out> ByRef value As Double) As String
Dim isSingle As Boolean = literal.GetTypeCharacter() = TypeCharacter.Single OrElse literal.GetTypeCharacter() = TypeCharacter.SingleLiteral
' Get the string representation of the value using The Round-trip ("R") Format Specifier.
' MSDN comments about "R" format specifier:
' The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value.
' This format is supported only for the Single, Double, and BigInteger types.
' When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and
' 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier.
' If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single.
' Hence the possible actual precision values are:
' (a) Single: 7 or 9 and
' (b) Double: 15 or 17
Dim valueText As String = GetValueStringCore(literal, isSingle, "R", value)
' Floating point values might be represented either in fixed point notation or scientific/exponent notation.
' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)):
' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and
' less than the precision specifier; otherwise, scientific notation is used.
'
' However, Dev11 pretty lister differs from this for floating point values with exponent < 0.
' Instead of "greater than -5" mentioned above, it uses fixed point notation as long as exponent is greater than "-(precision + 2)".
' For example, consider pretty listing for Single literals:
' (i) Precision = 7
' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation)
' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation)
' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation)
' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation)
' (ii) Precision = 9
' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation)
' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation)
' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation)
' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation)
'
' We replicate the same behavior below
Dim exponentIndex As Integer = valueText.IndexOf("E"c)
If exponentIndex > 0 Then
Dim exponent = Integer.Parse(valueText.Substring(exponentIndex + 1), CultureInfo.InvariantCulture)
If exponent < 0 Then
Dim defaultPrecision As Integer = If(isSingle, 7, 15)
Dim numSignificantDigits = exponentIndex - 1 ' subtract 1 for the decimal point
Dim actualPrecision As Integer = If(numSignificantDigits > defaultPrecision, defaultPrecision + 2, defaultPrecision)
If exponent > -(actualPrecision + 2) Then
' Convert valueText to floating point notation.
' Prepend "0.00000.."
Dim prefix = "0." + New String("0"c, -exponent - 1)
' Get the significant digits string.
Dim significantDigitsStr = valueText.Substring(0, exponentIndex)
' Remove the existing decimal point, if any, from valueText.
If significantDigitsStr.Length > 1 AndAlso significantDigitsStr(1) = "."c Then
significantDigitsStr = significantDigitsStr.Remove(1, 1)
End If
Return prefix + significantDigitsStr
End If
End If
End If
' Single.ToString(String) might return result in exponential notation, where the exponent is formatted to at least 2 digits.
' Dev11 pretty lister is identical in all cases except when the exponent is exactly 2 digit with a leading zero, e.g. "2.3E+08F" or "2.3E-08F".
' Dev11 pretty lists these cases to "2.3E+8F" or "2.3E-8F" respectively; we do the same here.
If isSingle Then
' Check if valueText ends with "E+XX" or "E-XX"
If valueText.Length > 4 Then
If valueText.Length = exponentIndex + 4 Then
' Trim zero for these two cases: "E+0X" or "E-0X"
If valueText(exponentIndex + 2) = "0"c Then
valueText = valueText.Remove(exponentIndex + 2, 1)
End If
End If
End If
End If
' If the value is integral, then append ".0" to the valueText.
If Not valueText.Contains("."c) Then
Return If(exponentIndex > 0, valueText.Insert(exponentIndex, ".0"), valueText + ".0")
End If
Return valueText
End Function
Private Shared Function GetValueStringCore(literal As SyntaxToken, isSingle As Boolean, formatSpecifier As String, <Out> ByRef value As Double) As String
If isSingle Then
Dim singleValue = DirectCast(literal.Value, Single)
value = singleValue
Return singleValue.ToString(formatSpecifier, CultureInfo.InvariantCulture)
Else
value = DirectCast(literal.Value, Double)
Return value.ToString(formatSpecifier, CultureInfo.InvariantCulture)
End If
End Function
Private Shared Function GetDecimalLiteralValueString(value As Decimal) As String
' CONSIDER: If the parsed value is integral, i.e. has no decimal point, we should insert ".0" before "D" in the valueText (similar to the pretty listing for float literals).
' CONSIDER: However, native VB compiler doesn't do so for decimal literals, we will maintain compatibility.
' CONSIDER: We may want to consider taking a breaking change and make this consistent between float and decimal literals.
Dim valueText = value.ToString(CultureInfo.InvariantCulture)
' Trim any redundant zeros after the decimal point.
' If all the digits after the decimal point are 0, then trim the decimal point as well.
Dim parts As String() = valueText.Split("."c)
If parts.Length() > 1 Then
' We might have something like "1.000E+100". Ensure we only truncate the zeros before "E".
Dim partsAfterDot = parts(1).Split("E"c)
Dim stringToTruncate As String = partsAfterDot(0)
Dim truncatedString = stringToTruncate.TrimEnd("0"c)
If Not String.Equals(truncatedString, stringToTruncate, StringComparison.Ordinal) Then
Dim integralPart As String = parts(0)
Dim fractionPartOpt As String = If(truncatedString.Length > 0, "." + truncatedString, "")
Dim exponentPartOpt As String = If(partsAfterDot.Length > 1, "E" + partsAfterDot(1), "")
Return integralPart + fractionPartOpt + exponentPartOpt
End If
End If
Return valueText
End Function
Private Function GetIntegerLiteralValueString(value As Object, base As LiteralBase) As String
Select Case base
Case LiteralBase.Decimal
Return CType(value, ULong).ToString(CultureInfo.InvariantCulture)
Case LiteralBase.Hexadecimal
Return "&H" + ConvertToULong(value).ToString("X")
Case LiteralBase.Octal
Dim val1 As ULong = ConvertToULong(value)
Return "&O" + ConvertToOctalString(val1)
Case LiteralBase.Binary
Dim asLong = CType(ConvertToULong(value), Long)
Return "&B" + Convert.ToString(asLong, 2)
Case Else
Throw ExceptionUtilities.UnexpectedValue(base)
End Select
End Function
Private Shared Function CreateLiteralToken(token As SyntaxToken, newValueString As String, newValue As Object) As SyntaxToken
' create a new token with valid token text and carries over annotations attached to original token to be a good citizen
' it might be replacing a token that has annotation injected by other code cleanups
Dim leading = If(token.LeadingTrivia.Count > 0, token.LeadingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))
Dim trailing = If(token.TrailingTrivia.Count > 0, token.TrailingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))
Select Case token.Kind
Case SyntaxKind.FloatingLiteralToken
Return token.CopyAnnotationsTo(SyntaxFactory.FloatingLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Double), trailing))
Case SyntaxKind.DecimalLiteralToken
Return token.CopyAnnotationsTo(SyntaxFactory.DecimalLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Decimal), trailing))
Case SyntaxKind.IntegerLiteralToken
Return token.CopyAnnotationsTo(SyntaxFactory.IntegerLiteralToken(leading, newValueString, token.GetBase().Value, token.GetTypeCharacter(), DirectCast(newValue, ULong), trailing))
Case Else
Throw ExceptionUtilities.UnexpectedValue(token.Kind)
End Select
End Function
Private Function ConvertToOctalString(value As ULong) As String
Dim exponent As ULong = value
Dim builder As New StringBuilder()
If value = 0 Then
Return "0"
End If
While (exponent > 0)
Dim remainder = exponent Mod 8UL
builder.Insert(0, remainder)
exponent = exponent \ 8UL
End While
Return builder.ToString()
End Function
Private Function HasOverflow(diagnostics As IEnumerable(Of Diagnostic)) As Boolean
Return diagnostics.Any(Function(diagnostic As Diagnostic) diagnostic.Id = "BC30036")
End Function
Private Function ConvertToULong(value As Object) As ULong
'Cannot convert directly to ULong from Short or Integer as negative numbers
'appear to have all bits above the current bit range set to 1
'so short value -32768 or binary 1000000000000000 becomes
'binary 1111111111111111111111111111111111111111111111111000000000000000
'or in decimal 18446744073709518848
'This will cause the subsequent conversion to a hex or octal string to output an incorrect value
If TypeOf (value) Is Short Then
Return CType(value, UShort)
ElseIf TypeOf (value) Is Integer Then
Return CType(value, UInteger)
Else
Return CType(value, ULong)
End If
End Function
End Class
End Class
End Namespace
|
MichalStrehovsky/roslyn
|
src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/ReduceTokensCodeCleanupProvider.vb
|
Visual Basic
|
apache-2.0
| 20,122
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18444
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("PA_8_W_Weinert.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
winny-/CPS-240
|
Assignments/PA 8 W Weinert/PA 8 W Weinert/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,723
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.0
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "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.ConsoleApplicationVB.My.MySettings
Get
Return Global.ConsoleApplicationVB.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
ParticularLabs/SetStartupProjects
|
src/SampleSolution/ConsoleApplicationVB/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,942
|
Imports System.Xml
Imports System.Windows.Forms
Imports ExcelDna.Integration
Imports System.IO
''' <summary>Dialog used to display and edit the CustomXMLPart utilized for storing the DBModif definitions</summary>
Public Class EditDBModifDef
''' <summary>the edited CustomXmlParts for the DBModif definitions</summary>
Private CustomXmlParts As Object
''' <summary>put the custom xml definition in the edit box for display/editing</summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub EditDBModifDef_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CustomXmlParts = ExcelDnaUtil.Application.ActiveWorkbook.CustomXMLParts.SelectByNamespace("DBModifDef")
' Make a StringWriter to hold the result.
Using sw As New System.IO.StringWriter()
' Make a XmlTextWriter to format the XML.
Using xml_writer As New XmlTextWriter(sw)
xml_writer.Formatting = Formatting.Indented
Dim doc As New XmlDocument()
doc.LoadXml(CustomXmlParts(1).XML)
doc.WriteTo(xml_writer)
xml_writer.Flush()
' Display the result.
Me.EditBox.Text = sw.ToString
End Using
End Using
End Sub
''' <summary>store the displayed/edited textbox content back into the custom xml definition, indluding validation feedback</summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub OKBtn_Click(sender As Object, e As EventArgs) Handles OKBtn.Click
' Make a StringWriter to reformat the indented XML.
Using sw As New System.IO.StringWriter()
' Make a XmlTextWriter to (un)format the XML.
Using xml_writer As New XmlTextWriter(sw)
' revert indentation...
xml_writer.Formatting = Formatting.None
Dim doc As New XmlDocument()
Try
' validate definition XML
Dim schemaString As String = My.Resources.SchemaFiles.DBModifDef
Dim schemadoc As XmlReader = XmlReader.Create(New StringReader(schemaString))
doc.Schemas.Add("DBModifDef", schemadoc)
Dim eventHandler As Schema.ValidationEventHandler = New Schema.ValidationEventHandler(AddressOf myValidationEventHandler)
doc.LoadXml(Me.EditBox.Text)
doc.Validate(eventHandler)
Catch ex As Exception
DBModifs.ErrorMsg("Problems with parsing changed definition: " + ex.Message, "Edit DB Modifier Definitions XML")
Exit Sub
End Try
doc.WriteTo(xml_writer)
xml_writer.Flush()
' store the result in CustomXmlParts
CustomXmlParts(1).Delete
CustomXmlParts.Add(sw.ToString)
End Using
End Using
Me.DialogResult = DialogResult.OK
Me.Close()
End Sub
''' <summary>validation handler for XML schema (DBModifDef) checking</summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Sub myValidationEventHandler(sender As Object, e As Schema.ValidationEventArgs)
' simply pass back Errors and Warnings as an exception
If e.Severity = Schema.XmlSeverityType.Error Or e.Severity = Schema.XmlSeverityType.Warning Then Throw New Exception(e.Message)
End Sub
''' <summary>no change was made to definition</summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub CancelBtn_Click(sender As Object, e As EventArgs) Handles CancelBtn.Click
Me.DialogResult = DialogResult.Cancel
Me.Close()
End Sub
''' <summary>show the current line and column for easier detection of problems in xml document</summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub EditBox_SelectionChanged(sender As Object, e As EventArgs) Handles EditBox.SelectionChanged
Me.PosIndex.Text = "Line: " + (Me.EditBox.GetLineFromCharIndex(Me.EditBox.SelectionStart) + 1).ToString + ", Column: " + (Me.EditBox.SelectionStart - Me.EditBox.GetFirstCharIndexOfCurrentLine + 1).ToString
End Sub
End Class
|
Excel-DNA/Samples
|
CustomXMLParts/EditDBModifDef.vb
|
Visual Basic
|
mit
| 4,332
|
Public Class XtfBathySnippet0
Public Property Id As UInt32
Public Property HeaderSize As UInt16
Public Property DataSize As UInt16
Public Property PingNumber As UInt32
Public Property Seconds As UInt32
Public Property Milliseconds As UInt32
Public Property Latency As UInt16
Public Property SonarId1 As UInt16
Public Property SonarId2 As UInt16
Public Property SonarModel As UInt16
Public Property Frequency As UInt16
Public Property SoundSpeed As UInt16
Public Property SampleRate As UInt16
Public Property PingRate As UInt16
Public Property Range As UInt16
Public Property Power As UInt16
Public Property Gain As UInt16
Public Property PulseWidth As UInt16
Public Property Spread As UInt16
Public Property Absorb As UInt16
Public Property ProjectorType As UInt16
Public Property ProjectorWidth As UInt16
Public Property SpacingNumerator As UInt16
Public Property SpacingDenominator As UInt16
Public Property ProjectorAngle As Int16
Public Property MinRange As UInt16
Public Property MaxRange As UInt16
Public Property MinDepth As UInt16
Public Property MaxDepth As UInt16
Public Property Filters As UInt16
Public Property Flags As UInt16
Public Property HeadTemp As Int16
Public Property BeamCount As UInt16
Public Sub New()
Id = &H534E5030
HeaderSize = 0
DataSize = 0
PingNumber = 0
Seconds = 0
Milliseconds = 0
Latency = 0
SonarId1 = 0
SonarId2 = 0
SonarModel = 0
Frequency = 0
SoundSpeed = 0
SampleRate = 0
PingRate = 0
Range = 0
Power = 0
Gain = 0
PulseWidth = 0
Spread = 0
Absorb = 0
ProjectorType = 0
ProjectorWidth = 0
SpacingNumerator = 0
SpacingDenominator = 0
ProjectorAngle = 0
MinRange = 0
MaxRange = 0
MinDepth = 0
MaxDepth = 0
Filters = 0
Flags = 0
HeadTemp = 0
BeamCount = 0
End Sub
Public Sub New(byteArray As Byte())
Dim chkNumber As UInt32
Id = &H534E5030
HeaderSize = 0
DataSize = 0
PingNumber = 0
Seconds = 0
Milliseconds = 0
Latency = 0
SonarId1 = 0
SonarId2 = 0
SonarModel = 0
Frequency = 0
SoundSpeed = 0
SampleRate = 0
PingRate = 0
Range = 0
Power = 0
Gain = 0
PulseWidth = 0
Spread = 0
Absorb = 0
ProjectorType = 0
ProjectorWidth = 0
SpacingNumerator = 0
SpacingDenominator = 0
ProjectorAngle = 0
MinRange = 0
MaxRange = 0
MinDepth = 0
MaxDepth = 0
Filters = 0
Flags = 0
HeadTemp = 0
BeamCount = 0
Using dp As New BinaryReader(ByteArrayToMemoryStream(byteArray))
chkNumber = dp.ReadUInt32
If chkNumber = &H534E5030 Then
HeaderSize = dp.ReadUInt16
DataSize = dp.ReadUInt16
PingNumber = dp.ReadUInt32
Seconds = dp.ReadUInt32
Milliseconds = dp.ReadUInt32
Latency = dp.ReadUInt16
SonarId1 = dp.ReadUInt16
SonarId2 = dp.ReadUInt16
SonarModel = dp.ReadUInt16
Frequency = dp.ReadUInt16
SoundSpeed = dp.ReadUInt16
SampleRate = dp.ReadUInt16
PingRate = dp.ReadUInt16
Range = dp.ReadUInt16
Power = dp.ReadUInt16
Gain = dp.ReadUInt16
PulseWidth = dp.ReadUInt16
Spread = dp.ReadUInt16
Absorb = dp.ReadUInt16
ProjectorType = dp.ReadUInt16
ProjectorWidth = dp.ReadUInt16
SpacingNumerator = dp.ReadUInt16
SpacingDenominator = dp.ReadUInt16
ProjectorAngle = dp.ReadInt16
MinRange = dp.ReadUInt16
MaxRange = dp.ReadUInt16
MinDepth = dp.ReadUInt16
MaxDepth = dp.ReadUInt16
Filters = dp.ReadUInt16
Flags = dp.ReadUInt16
HeadTemp = dp.ReadInt16
BeamCount = dp.ReadUInt16
Else
'something wrong
End If
End Using
End Sub
End Class
|
jaksg82/XtfViewer
|
jakxtflib/xtfBathySnippet0.vb
|
Visual Basic
|
mit
| 4,520
|
Imports ExcelDna.Integration
Imports ExcelDna.IntelliSense
Public Class AddIn
Implements IExcelAddIn
Public Sub AutoOpen() Implements IExcelAddIn.AutoOpen
IntelliSenseServer.Install()
End Sub
Public Sub AutoClose() Implements IExcelAddIn.AutoClose
IntelliSenseServer.Uninstall()
End Sub
End Class
|
Excel-DNA/Samples
|
ArrayMap/AddIn.vb
|
Visual Basic
|
mit
| 339
|
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' Information about this assembly is defined by the following
' attributes.
'
' change them to the information which is associated with the assembly
' you compile.
<assembly: AssemblyTitle("GFWToVBNetConverter")>
<assembly: AssemblyDescription("")>
<assembly: AssemblyConfiguration("")>
<assembly: AssemblyCompany("")>
<assembly: AssemblyProduct("GFWToVBNetConverter")>
<assembly: AssemblyCopyright("Copyright 2016")>
<assembly: AssemblyTrademark("")>
<assembly: AssemblyCulture("")>
' This sets the default COM visibility of types in the assembly to invisible.
' If you need to expose a type to COM, use <ComVisible(true)> on that type.
<assembly: ComVisible(False)>
' The assembly version has following format :
'
' Major.Minor.Build.Revision
'
' You can specify all values by your own or you can build default build and revision
' numbers with the '*' character (the default):
<assembly: AssemblyVersion("1.0.*")>
|
codeprof/GFA-Basic-to-VB.Net-converter
|
Converter/GFWToVBNetConverter/GFWToVBNetConverter/Properties/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,061
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("FINALPROJECT_SIMON.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
|
Matthew-Christopher/SimonSaysVB
|
FINALPROJECT_SIMON/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,789
|
Imports System.Dynamic
Imports System.Management.Automation.Runspaces
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CSharp.Scripting
Imports Microsoft.CodeAnalysis.Scripting
Public Class Scripting
Shared Property App As New ScriptingApp
Shared Sub RunCSharp(code As String, Optional hideErrors As Boolean = False)
RunCSharpAsync(code, hideErrors).Wait()
End Sub
Private Shared Async Function RunCSharpAsync(code As String, Optional hideErrors As Boolean = False) As Task(Of Object)
Try
Dim options = ScriptOptions.Default.WithImports(
"StaxRip", "System.Linq", "System.IO", "System.Text.RegularExpressions").
WithReferences(GetType(Scripting).Assembly,
GetType(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly)
Await CSharpScript.Create(code, options).RunAsync()
Catch ex As Exception
If Not hideErrors Then MsgError(ex.Message)
End Try
End Function
Shared Sub RunPowershell(code As String)
Using runspace = RunspaceFactory.CreateRunspace()
runspace.Open()
runspace.SessionStateProxy.SetVariable("app", App)
Using pipeline = runspace.CreatePipeline()
pipeline.Commands.AddScript(code)
Try
pipeline.Invoke()
Catch ex As Exception
MsgError(ex.Message)
End Try
End Using
End Using
End Sub
End Class
Public Class ScriptingApp
Inherits DynamicObject
Public Overrides Function TryInvokeMember(
binder As InvokeMemberBinder,
args() As Object, ByRef result As Object) As Boolean
Try
g.MainForm.CommandManager.Process(binder.Name, args)
Return True
Catch ex As Exception
g.ShowException(ex)
result = Nothing
Return False
End Try
End Function
End Class
|
amccool/staxrip
|
General/Scripting.vb
|
Visual Basic
|
mit
| 2,009
|
Public Class FormA
Public Sub ShowNewText(text As String)
Me.Label1.Text = text
End Sub
End Class
|
Koopakiller/Forum-Samples
|
Other/0f323ad558c64fa6b792a7175daf8878/WindowsApp1/FormA.vb
|
Visual Basic
|
mit
| 116
|
Imports SistFoncreagro.BussinessEntities
Imports SistFoncreagro.DataAccess
Public Class InteresadosBL : Implements IInteresadosBL
Dim factoryrepository As IInteresadosRepository
Public Sub New()
factoryrepository = New InteresadosRepository
End Sub
Public Sub DeleteINTERESADOS(ByVal IdInteresado As Integer) Implements IInteresadosBL.DeleteINTERESADOS
factoryrepository.DeleteINTERESADOS(IdInteresado)
End Sub
Public Function GetINTERESADOByParametro(ByVal Parametro As String) As System.Collections.Generic.List(Of BussinessEntities.Interesados) Implements IInteresadosBL.GetINTERESADOByParametro
Return factoryrepository.GetINTERESADOByParametro(Parametro)
End Function
Public Function GetINTERESADOSByIdInteresado(ByVal IdInteresado As Integer) As BussinessEntities.Interesados Implements IInteresadosBL.GetINTERESADOSByIdInteresado
Return factoryrepository.GetINTERESADOSByIdInteresado(IdInteresado)
End Function
Public Function SaveINTERESADO(ByVal _Interesados As BussinessEntities.Interesados) As Integer Implements IInteresadosBL.SaveINTERESADO
Return factoryrepository.SaveINTERESADO(_Interesados)
End Function
Public Function VerifyInteresado(dni As String) As Integer Implements IInteresadosBL.VerifyInteresado
Return factoryrepository.VerifyInteresado(dni)
End Function
Public Function VerifyInteresado1(nombre As String) As Integer Implements IInteresadosBL.VerifyInteresado1
Return factoryrepository.VerifyInteresado1(nombre)
End Function
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/InteresadosBL.vb
|
Visual Basic
|
mit
| 1,591
|
' 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
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.Implementation.Formatting
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Friend Class TestState
Inherits AbstractCommandHandlerTestState
Private Const timeoutMs = 60000
Private Const editorTimeoutMs = 60000
Friend Const RoslynItem = "RoslynItem"
Friend ReadOnly EditorCompletionCommandHandler As ICommandHandler
Friend ReadOnly CompletionPresenterProvider As ICompletionPresenterProvider
Protected ReadOnly SessionTestState As IIntelliSenseTestState
Private ReadOnly SignatureHelpBeforeCompletionCommandHandler As SignatureHelpBeforeCompletionCommandHandler
Protected ReadOnly SignatureHelpAfterCompletionCommandHandler As SignatureHelpAfterCompletionCommandHandler
Private ReadOnly FormatCommandHandler As FormatCommandHandler
Private Shared s_lazyEntireAssemblyCatalogWithCSharpAndVisualBasicWithoutCompletionTestParts As Lazy(Of ComposableCatalog) =
New Lazy(Of ComposableCatalog)(Function()
Return TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.
WithoutPartsOfTypes({
GetType(IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)),
GetType(FormatCommandHandler)}).
WithParts({
GetType(TestSignatureHelpPresenter),
GetType(IntelliSenseTestState),
GetType(MockCompletionPresenterProvider)
})
End Function)
Private Shared ReadOnly Property EntireAssemblyCatalogWithCSharpAndVisualBasicWithoutCompletionTestParts As ComposableCatalog
Get
Return s_lazyEntireAssemblyCatalogWithCSharpAndVisualBasicWithoutCompletionTestParts.Value
End Get
End Property
Private Shared s_lazyExportProviderFactoryWithCSharpAndVisualBasicWithoutCompletionTestParts As Lazy(Of IExportProviderFactory) =
New Lazy(Of IExportProviderFactory)(Function()
Return ExportProviderCache.GetOrCreateExportProviderFactory(EntireAssemblyCatalogWithCSharpAndVisualBasicWithoutCompletionTestParts)
End Function)
Private Shared ReadOnly Property ExportProviderFactoryWithCSharpAndVisualBasicWithoutCompletionTestParts As IExportProviderFactory
Get
Return s_lazyExportProviderFactoryWithCSharpAndVisualBasicWithoutCompletionTestParts.Value
End Get
End Property
Friend ReadOnly Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession
Get
Return SessionTestState.CurrentSignatureHelpPresenterSession
End Get
End Property
' Do not call directly. Use TestStateFactory
Friend Sub New(workspaceElement As XElement,
excludedTypes As List(Of Type),
extraExportedTypes As List(Of Type),
includeFormatCommandHandler As Boolean,
workspaceKind As String,
Optional makeSeparateBufferForCursor As Boolean = False,
Optional roles As ImmutableArray(Of String) = Nothing)
MyBase.New(workspaceElement, GetExportProvider(excludedTypes, extraExportedTypes, includeFormatCommandHandler), workspaceKind:=workspaceKind, makeSeparateBufferForCursor, roles)
' The current default timeout defined in the Editor may not work on slow virtual test machines.
' Need to use a safe timeout there to follow real code paths.
MyBase.TextView.Options.GlobalOptions.SetOptionValue(DefaultOptions.ResponsiveCompletionThresholdOptionId, editorTimeoutMs)
Dim languageServices = Me.Workspace.CurrentSolution.Projects.First().LanguageServices
Dim language = languageServices.Language
Me.SessionTestState = GetExportedValue(Of IIntelliSenseTestState)()
Me.SignatureHelpBeforeCompletionCommandHandler = GetExportedValue(Of SignatureHelpBeforeCompletionCommandHandler)()
Me.SignatureHelpAfterCompletionCommandHandler = GetExportedValue(Of SignatureHelpAfterCompletionCommandHandler)()
Me.FormatCommandHandler = If(includeFormatCommandHandler, GetExportedValue(Of FormatCommandHandler)(), Nothing)
CompletionPresenterProvider = GetExportedValues(Of ICompletionPresenterProvider)().
Single(Function(e As ICompletionPresenterProvider) e.GetType().FullName = "Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense.MockCompletionPresenterProvider")
EditorCompletionCommandHandler = GetExportedValues(Of ICommandHandler)().
Single(Function(e As ICommandHandler) e.GetType().Name = PredefinedCompletionNames.CompletionCommandHandler)
End Sub
Private Overloads Shared Function GetExportProvider(excludedTypes As List(Of Type),
extraExportedTypes As List(Of Type),
includeFormatCommandHandler As Boolean) As ExportProvider
If (excludedTypes Is Nothing OrElse excludedTypes.Count = 0) AndAlso
(extraExportedTypes Is Nothing OrElse extraExportedTypes.Count = 0) AndAlso
Not includeFormatCommandHandler Then
Return ExportProviderFactoryWithCSharpAndVisualBasicWithoutCompletionTestParts.CreateExportProvider()
End If
Dim combinedExcludedTypes = CombineExcludedTypes(excludedTypes, includeFormatCommandHandler)
Dim extraParts = ExportProviderCache.CreateTypeCatalog(CombineExtraTypes(If(extraExportedTypes, New List(Of Type))))
Return GetExportProvider(combinedExcludedTypes, extraParts)
End Function
#Region "Editor Related Operations"
Protected Overloads Sub ExecuteTypeCharCommand(args As TypeCharCommandArgs, finalHandler As Action, context As CommandExecutionContext, completionCommandHandler As IChainedCommandHandler(Of TypeCharCommandArgs))
Dim sigHelpHandler = DirectCast(SignatureHelpBeforeCompletionCommandHandler, IChainedCommandHandler(Of TypeCharCommandArgs))
Dim formatHandler = DirectCast(FormatCommandHandler, IChainedCommandHandler(Of TypeCharCommandArgs))
If formatHandler Is Nothing Then
sigHelpHandler.ExecuteCommand(
args, Sub() completionCommandHandler.ExecuteCommand(
args, finalHandler, context), context)
Else
formatHandler.ExecuteCommand(
args, Sub() sigHelpHandler.ExecuteCommand(
args, Sub() completionCommandHandler.ExecuteCommand(
args, finalHandler, context), context), context)
End If
End Sub
Public Overloads Sub SendTab()
Dim handler = GetHandler(Of IChainedCommandHandler(Of TabKeyCommandArgs))()
MyBase.SendTab(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() EditorOperations.InsertText(vbTab))
End Sub
Public Overloads Sub SendReturn()
Dim handler = GetHandler(Of IChainedCommandHandler(Of ReturnKeyCommandArgs))()
MyBase.SendReturn(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() EditorOperations.InsertNewLine())
End Sub
Public Overrides Sub SendBackspace()
Dim compHandler = GetHandler(Of IChainedCommandHandler(Of BackspaceKeyCommandArgs))()
MyBase.SendBackspace(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendBackspace)
End Sub
Public Overrides Sub SendDelete()
Dim compHandler = GetHandler(Of IChainedCommandHandler(Of DeleteKeyCommandArgs))()
MyBase.SendDelete(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendDelete)
End Sub
Public Sub SendDeleteToSpecificViewAndBuffer(view As IWpfTextView, buffer As ITextBuffer)
Dim compHandler = GetHandler(Of IChainedCommandHandler(Of DeleteKeyCommandArgs))()
compHandler.ExecuteCommand(New DeleteKeyCommandArgs(view, buffer), AddressOf MyBase.SendDelete, TestCommandExecutionContext.Create())
End Sub
Private Overloads Sub ExecuteTypeCharCommand(args As TypeCharCommandArgs, finalHandler As Action, context As CommandExecutionContext)
Dim compHandler = GetHandler(Of IChainedCommandHandler(Of TypeCharCommandArgs))()
ExecuteTypeCharCommand(args, finalHandler, context, compHandler)
End Sub
Public Overloads Sub SendTypeChars(typeChars As String)
MyBase.SendTypeChars(typeChars, Sub(a, n, c) ExecuteTypeCharCommand(a, n, c))
End Sub
Public Overloads Sub SendEscape()
MyBase.SendEscape(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() Return)
End Sub
Public Overloads Sub SendDownKey()
MyBase.SendDownKey(
Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c),
Sub()
EditorOperations.MoveLineDown(extendSelection:=False)
End Sub)
End Sub
Public Overloads Sub SendUpKey()
MyBase.SendUpKey(
Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c),
Sub()
EditorOperations.MoveLineUp(extendSelection:=False)
End Sub)
End Sub
Public Overloads Sub SendPageUp()
Dim handler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of PageUpKeyCommandArgs))
MyBase.SendPageUp(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendCut()
MyBase.SendCut(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendPaste()
MyBase.SendPaste(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendInvokeCompletionList()
MyBase.SendInvokeCompletionList(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendInsertSnippetCommand()
MyBase.SendInsertSnippetCommand(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendSurroundWithCommand()
MyBase.SendSurroundWithCommand(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendSave()
MyBase.SendSave(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Sub SendSelectAll()
MyBase.SendSelectAll(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendDeleteWordToLeft()
Dim compHandler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of WordDeleteToStartCommandArgs))
MyBase.SendWordDeleteToStart(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendDeleteWordToLeft)
End Sub
Public Overloads Sub SendToggleCompletionMode()
Dim handler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of ToggleCompletionModeCommandArgs))
MyBase.SendToggleCompletionMode(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Protected Function GetHandler(Of T As ICommandHandler)() As T
Return DirectCast(EditorCompletionCommandHandler, T)
End Function
#End Region
#Region "Completion Operations"
Public Async Function SendCommitUniqueCompletionListItemAsync() As Task
Await WaitForAsynchronousOperationsAsync()
' When we send the commit completion list item, it processes asynchronously; we can find out when it's complete
' by seeing that either the items are updated or the list is dismissed. We'll use a TaskCompletionSource to track
' when it's done which will release an async token.
Dim sessionComplete = New TaskCompletionSource(Of Object)()
Dim asynchronousOperationListenerProvider = Workspace.ExportProvider.GetExportedValue(Of AsynchronousOperationListenerProvider)()
Dim asyncToken = asynchronousOperationListenerProvider.GetListener(FeatureAttribute.CompletionSet) _
.BeginAsyncOperation("SendCommitUniqueCompletionListItemAsync")
#Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed
sessionComplete.Task.CompletesAsyncOperation(asyncToken)
#Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed
Dim itemsUpdatedHandler = Sub(sender As Object, e As Data.ComputedCompletionItemsEventArgs)
' If there is more than one item left, then it means this was the filter operation that resulted and we're done. Otherwise we know a
' Dismiss operation is coming so we should wait for it.
If e.Items.Items.Select(Function(i) i.FilterText).Skip(1).Any() Then
Task.Run(Sub()
Thread.Sleep(5000)
sessionComplete.TrySetResult(Nothing)
End Sub)
End If
End Sub
Dim sessionDismissedHandler = Sub(sender As Object, e As EventArgs) sessionComplete.TrySetResult(Nothing)
Dim session As IAsyncCompletionSession
Dim addHandlers = Sub(sender As Object, e As Data.CompletionTriggeredEventArgs)
AddHandler e.CompletionSession.ItemsUpdated, itemsUpdatedHandler
AddHandler e.CompletionSession.Dismissed, sessionDismissedHandler
session = e.CompletionSession
End Sub
Dim asyncCompletionBroker As IAsyncCompletionBroker = GetExportedValue(Of IAsyncCompletionBroker)()
session = asyncCompletionBroker.GetSession(TextView)
If session Is Nothing Then
AddHandler asyncCompletionBroker.CompletionTriggered, addHandlers
Else
' A session was already active so we'll fake the event
addHandlers(asyncCompletionBroker, New Data.CompletionTriggeredEventArgs(session, TextView))
End If
MyBase.SendCommitUniqueCompletionListItem(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return)
Await WaitForAsynchronousOperationsAsync()
RemoveHandler session.ItemsUpdated, itemsUpdatedHandler
RemoveHandler session.Dismissed, sessionDismissedHandler
RemoveHandler asyncCompletionBroker.CompletionTriggered, addHandlers
' It's possible for the wait to bail and give up if it was clear nothing was completing; ensure we clean up our
' async token so as not to interfere with later tests.
sessionComplete.TrySetResult(Nothing)
End Function
Public Async Function AssertNoCompletionSession() As Task
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session Is Nothing Then
Return
End If
If session.IsDismissed Then
Return
End If
Dim completionItems = session.GetComputedItems(CancellationToken.None)
' During the computation we can explicitly dismiss the session or we can return no items.
' Each of these conditions mean that there is no active completion.
Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0, "AssertNoCompletionSession")
End Function
Public Sub AssertNoCompletionSessionWithNoBlock()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session Is Nothing Then
Return
End If
If session.IsDismissed Then
Return
End If
' If completionItems cannot be calculated in 5 seconds, no session exists.
Dim task1 = Task.Delay(5000)
Dim task2 = Task.Run(
Sub()
Dim completionItems = session.GetComputedItems(CancellationToken.None)
' In the non blocking mode, we are not interested for a session appeared later than in 5 seconds.
If task1.Status = TaskStatus.Running Then
' During the computation we can explicitly dismiss the session or we can return no items.
' Each of these conditions mean that there is no active completion.
Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0)
End If
End Sub)
Task.WaitAny(task1, task2)
End Sub
Public Async Function AssertCompletionSession(Optional projectionsView As ITextView = Nothing) As Task
Await WaitForAsynchronousOperationsAsync()
Dim view = If(projectionsView, TextView)
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view)
Assert.NotNull(session)
End Function
Public Async Function AssertCompletionItemsDoNotContainAny(ParamArray displayText As String()) As Task
Await WaitForAsynchronousOperationsAsync()
Dim items = GetCompletionItems()
Assert.False(displayText.Any(Function(v) items.Any(Function(i) i.DisplayText = v)))
End Function
Public Async Function AssertCompletionItemsContainAll(ParamArray displayText As String()) As Task
Await WaitForAsynchronousOperationsAsync()
Dim items = GetCompletionItems()
Assert.True(displayText.All(Function(v) items.Any(Function(i) i.DisplayText = v)))
End Function
Public Async Function AssertCompletionItemsContain(displayText As String, displayTextSuffix As String) As Task
Await WaitForAsynchronousOperationsAsync()
Dim items = GetCompletionItems()
Assert.True(items.Any(Function(i) i.DisplayText = displayText AndAlso i.DisplayTextSuffix = displayTextSuffix))
End Function
Public Sub AssertItemsInOrder(expectedOrder As String())
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None).Items
Assert.Equal(expectedOrder.Count, items.Count)
For i = 0 To expectedOrder.Count - 1
Assert.Equal(expectedOrder(i), items(i).DisplayText)
Next
End Sub
Public Sub AssertItemsInOrder(expectedOrder As (String, String)())
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None).Items
Assert.Equal(expectedOrder.Count, items.Count)
For i = 0 To expectedOrder.Count - 1
Assert.Equal(expectedOrder(i).Item1, items(i).DisplayText)
Assert.Equal(expectedOrder(i).Item2, items(i).Suffix)
Next
End Sub
Public Async Function AssertSelectedCompletionItem(
Optional displayText As String = Nothing,
Optional displayTextSuffix As String = Nothing,
Optional description As String = Nothing,
Optional isSoftSelected As Boolean? = Nothing,
Optional isHardSelected As Boolean? = Nothing,
Optional shouldFormatOnCommit As Boolean? = Nothing,
Optional inlineDescription As String = Nothing,
Optional automationText As String = Nothing,
Optional projectionsView As ITextView = Nothing) As Task
Await WaitForAsynchronousOperationsAsync()
Dim view = If(projectionsView, TextView)
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None)
If isSoftSelected.HasValue Then
If isSoftSelected.Value Then
Assert.True(items.UsesSoftSelection, "Current completion is not soft-selected. Expected: soft-selected")
Else
Assert.False(items.UsesSoftSelection, "Current completion is soft-selected. Expected: not soft-selected")
End If
End If
If isHardSelected.HasValue Then
If isHardSelected.Value Then
Assert.True(Not items.UsesSoftSelection, "Current completion is not hard-selected. Expected: hard-selected")
Else
Assert.True(items.UsesSoftSelection, "Current completion is hard-selected. Expected: not hard-selected")
End If
End If
If displayText IsNot Nothing Then
Assert.NotNull(items.SelectedItem)
If displayTextSuffix IsNot Nothing Then
Assert.NotNull(items.SelectedItem)
Assert.Equal(displayText + displayTextSuffix, items.SelectedItem.DisplayText)
Else
Assert.Equal(displayText, items.SelectedItem.DisplayText)
End If
End If
If shouldFormatOnCommit.HasValue Then
Assert.Equal(shouldFormatOnCommit.Value, GetRoslynCompletionItem(items.SelectedItem).Rules.FormatOnCommit)
End If
If description IsNot Nothing Then
Dim itemDescription = Await GetSelectedItemDescriptionAsync()
Assert.Equal(description, itemDescription.Text)
End If
If inlineDescription IsNot Nothing Then
Assert.Equal(inlineDescription, items.SelectedItem.Suffix)
End If
If automationText IsNot Nothing Then
Assert.Equal(automationText, items.SelectedItem.AutomationText)
End If
End Function
Public Async Function GetSelectedItemDescriptionAsync() As Task(Of CompletionDescription)
Dim document = Me.Workspace.CurrentSolution.Projects.First().Documents.First()
Dim service = CompletionService.GetService(document)
Dim roslynItem = GetSelectedItem()
Return Await service.GetDescriptionAsync(document, roslynItem)
End Function
Public Sub AssertCompletionItemExpander(isAvailable As Boolean, isSelected As Boolean)
Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter)
Dim expander = presenter.GetExpander()
If Not isAvailable Then
Assert.False(isSelected)
Assert.Null(expander)
Else
Assert.NotNull(expander)
Assert.Equal(expander.IsSelected, isSelected)
End If
End Sub
Public Sub SetCompletionItemExpanderState(isSelected As Boolean)
Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter)
Dim expander = presenter.GetExpander()
Assert.NotNull(expander)
presenter.SetExpander(isSelected)
End Sub
Public Async Function AssertSessionIsNothingOrNoCompletionItemLike(text As String) As Task
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If Not session Is Nothing Then
Await AssertCompletionItemsDoNotContainAny(text)
End If
End Function
Public Function GetSelectedItem() As CompletionItem
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None)
Return GetRoslynCompletionItem(items.SelectedItem)
End Function
Public Sub CalculateItemsIfSessionExists()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session IsNot Nothing Then
Dim item = session.GetComputedItems(CancellationToken.None).SelectedItem
End If
End Sub
Public Function GetCompletionItems() As IList(Of CompletionItem)
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Return session.GetComputedItems(CancellationToken.None).Items.Select(Function(item) GetRoslynCompletionItem(item)).ToList()
End Function
Private Shared Function GetRoslynCompletionItem(item As Data.CompletionItem) As CompletionItem
Return If(item IsNot Nothing, DirectCast(item.Properties(RoslynItem), CompletionItem), Nothing)
End Function
Public Sub RaiseFiltersChanged(args As ImmutableArray(Of Data.CompletionFilterWithState))
Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter)
Dim newArgs = New Data.CompletionFilterChangedEventArgs(args)
presenter.TriggerFiltersChanged(Me, newArgs)
End Sub
Public Function GetCompletionItemFilters() As ImmutableArray(Of Data.CompletionFilterWithState)
Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter)
Return presenter.GetFilters()
End Function
Public Function HasSuggestedItem() As Boolean
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim computedItems = session.GetComputedItems(CancellationToken.None)
Return computedItems.SuggestionItem IsNot Nothing
End Function
Public Function IsSoftSelected() As Boolean
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim computedItems = session.GetComputedItems(CancellationToken.None)
Return computedItems.UsesSoftSelection
End Function
Public Sub SendSelectCompletionItem(displayText As String)
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Dim operations = DirectCast(session, IAsyncCompletionSessionOperations)
operations.SelectCompletionItem(session.GetComputedItems(CancellationToken.None).Items.Single(Function(i) i.DisplayText = displayText))
End Sub
Public Async Function WaitForUIRenderedAsync() As Task
Await WaitForAsynchronousOperationsAsync()
Dim tcs = New TaskCompletionSource(Of Boolean)
Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(TextView), MockCompletionPresenter)
Dim uiUpdated As EventHandler(Of Data.CompletionItemSelectedEventArgs)
uiUpdated = Sub()
RemoveHandler presenter.UiUpdated, uiUpdated
tcs.TrySetResult(True)
End Sub
AddHandler presenter.UiUpdated, uiUpdated
Dim ct = New CancellationTokenSource(timeoutMs)
ct.Token.Register(Sub() tcs.TrySetCanceled(), useSynchronizationContext:=False)
Await tcs.Task.ConfigureAwait(True)
End Function
Public Overloads Sub SendTypeCharsToSpecificViewAndBuffer(typeChars As String, view As IWpfTextView, buffer As ITextBuffer)
For Each ch In typeChars
Dim localCh = ch
ExecuteTypeCharCommand(New TypeCharCommandArgs(view, buffer, localCh), Sub() EditorOperations.InsertText(localCh.ToString()), TestCommandExecutionContext.Create())
Next
End Sub
Public Async Function AssertLineTextAroundCaret(expectedTextBeforeCaret As String, expectedTextAfterCaret As String) As Task
Await WaitForAsynchronousOperationsAsync()
Dim actual = GetLineTextAroundCaretPosition()
Assert.Equal(expectedTextBeforeCaret, actual.TextBeforeCaret)
Assert.Equal(expectedTextAfterCaret, actual.TextAfterCaret)
End Function
Public Sub NavigateToDisplayText(targetText As String)
Dim currentText = GetSelectedItem().DisplayText
' GetComputedItems provided by the Editor for tests does not guarantee that
' the order of items match the order of items actually displayed in the completion popup.
' For example, they put starred items (intellicode) below non-starred ones.
' And the order they display those items in the UI is opposite.
' Therefore, we do the full traverse: down to the bottom and if not found up to the top.
Do While currentText <> targetText
SendDownKey()
Dim newText = GetSelectedItem().DisplayText
If currentText = newText Then
' Nothing found on going down. Try going up
Do While currentText <> targetText
SendUpKey()
newText = GetSelectedItem().DisplayText
Assert.True(newText <> currentText, "Reached the bottom, then the top and didn't find the match")
currentText = newText
Loop
End If
currentText = newText
Loop
End Sub
#End Region
#Region "Signature Help Operations"
Public Overloads Sub SendInvokeSignatureHelp()
Dim handler = DirectCast(SignatureHelpBeforeCompletionCommandHandler, IChainedCommandHandler(Of InvokeSignatureHelpCommandArgs))
MyBase.SendInvokeSignatureHelp(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overloads Async Function AssertNoSignatureHelpSession(Optional block As Boolean = True) As Task
If block Then
Await WaitForAsynchronousOperationsAsync()
End If
Assert.Null(Me.CurrentSignatureHelpPresenterSession)
End Function
Public Overloads Async Function AssertSignatureHelpSession() As Task
Await WaitForAsynchronousOperationsAsync()
Assert.NotNull(Me.CurrentSignatureHelpPresenterSession)
End Function
Public Overloads Function GetSignatureHelpItems() As IList(Of SignatureHelpItem)
Return CurrentSignatureHelpPresenterSession.SignatureHelpItems
End Function
Public Async Function AssertSignatureHelpItemsContainAll(displayText As String()) As Task
Await WaitForAsynchronousOperationsAsync()
Assert.True(displayText.All(Function(v) CurrentSignatureHelpPresenterSession.SignatureHelpItems.Any(
Function(i) GetDisplayText(i, CurrentSignatureHelpPresenterSession.SelectedParameter.Value) = v)))
End Function
Public Async Function AssertSelectedSignatureHelpItem(Optional displayText As String = Nothing,
Optional documentation As String = Nothing,
Optional selectedParameter As String = Nothing) As Task
Await WaitForAsynchronousOperationsAsync()
If displayText IsNot Nothing Then
Assert.Equal(displayText, GetDisplayText(Me.CurrentSignatureHelpPresenterSession.SelectedItem, Me.CurrentSignatureHelpPresenterSession.SelectedParameter.Value))
End If
If documentation IsNot Nothing Then
Assert.Equal(documentation, Me.CurrentSignatureHelpPresenterSession.SelectedItem.DocumentationFactory(CancellationToken.None).GetFullText())
End If
If selectedParameter IsNot Nothing Then
Assert.Equal(selectedParameter, GetDisplayText(
Me.CurrentSignatureHelpPresenterSession.SelectedItem.Parameters(
Me.CurrentSignatureHelpPresenterSession.SelectedParameter.Value).DisplayParts))
End If
End Function
#End Region
#Region "Helpers"
Private Shared Function CombineExcludedTypes(excludedTypes As IList(Of Type), includeFormatCommandHandler As Boolean) As IList(Of Type)
Dim result = New List(Of Type) From {
GetType(IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession))
}
If Not includeFormatCommandHandler Then
result.Add(GetType(FormatCommandHandler))
End If
If excludedTypes IsNot Nothing Then
result.AddRange(excludedTypes)
End If
Return result
End Function
Private Shared Function CombineExtraTypes(extraExportedTypes As IList(Of Type)) As IList(Of Type)
Dim result = New List(Of Type) From {
GetType(TestSignatureHelpPresenter),
GetType(IntelliSenseTestState),
GetType(MockCompletionPresenterProvider)
}
If extraExportedTypes IsNot Nothing Then
result.AddRange(extraExportedTypes)
End If
Return result
End Function
Private Shared Function GetDisplayText(item As SignatureHelpItem, selectedParameter As Integer) As String
Dim suffix = If(selectedParameter < item.Parameters.Count,
GetDisplayText(item.Parameters(selectedParameter).SuffixDisplayParts),
String.Empty)
Return String.Join(
String.Empty,
GetDisplayText(item.PrefixDisplayParts),
String.Join(
GetDisplayText(item.SeparatorDisplayParts),
item.Parameters.Select(Function(p) GetDisplayText(p.DisplayParts))),
GetDisplayText(item.SuffixDisplayParts),
suffix)
End Function
Private Shared Function GetDisplayText(parts As IEnumerable(Of TaggedText)) As String
Return String.Join(String.Empty, parts.Select(Function(p) p.ToString()))
End Function
#End Region
End Class
End Namespace
|
davkean/roslyn
|
src/EditorFeatures/TestUtilities2/Intellisense/TestState.vb
|
Visual Basic
|
apache-2.0
| 37,503
|
' Copyright 2015, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201502
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201502
''' <summary>
''' This code example adds campaigns. To get campaigns, run GetCampaigns.vb.
'''
''' Tags: CampaignService.mutate
''' </summary>
Public Class AddCampaigns
Inherits ExampleBase
''' <summary>
''' Number of items being added / updated in this code example.
''' </summary>
Const NUM_ITEMS As Integer = 5
''' <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 AddCampaigns
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 adds campaigns. To get campaigns, run GetCampaigns.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 BudgetService.
Dim budgetService As BudgetService = user.GetService( _
AdWordsService.v201502.BudgetService)
' Get the CampaignService.
Dim campaignService As CampaignService = user.GetService( _
AdWordsService.v201502.CampaignService)
' Create the campaign budget.
Dim budget As New Budget
budget.name = "Interplanetary Cruise Budget #" & ExampleUtilities.GetRandomString
budget.period = BudgetBudgetPeriod.DAILY
budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
budget.amount = New Money
budget.amount.microAmount = 50000000
Dim budgetOperation As New BudgetOperation
budgetOperation.operator = [Operator].ADD
budgetOperation.operand = budget
Try
Dim budgetRetval As BudgetReturnValue = budgetService.mutate(New BudgetOperation() _
{budgetOperation})
budget = budgetRetval.value(0)
Catch ex As Exception
Throw New System.ApplicationException("Failed to add shared budget.", ex)
End Try
Dim operations As New List(Of CampaignOperation)
For i As Integer = 1 To NUM_ITEMS
' Create the campaign.
Dim campaign As New Campaign
campaign.name = "Interplanetary Cruise #" & ExampleUtilities.GetRandomString
campaign.status = CampaignStatus.PAUSED
Dim biddingConfig As New BiddingStrategyConfiguration()
biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPM
' Optional: also provide matching bidding scheme.
biddingConfig.biddingScheme = New ManualCpmBiddingScheme()
campaign.biddingStrategyConfiguration = biddingConfig
' Set the campaign budget.
campaign.budget = New Budget
campaign.budget.budgetId = budget.budgetId
campaign.advertisingChannelType = AdvertisingChannelType.SEARCH
' Set targetContentNetwork true. Other network targeting is not available
' for Ad Exchange Buyers.
campaign.networkSetting = New NetworkSetting
campaign.networkSetting.targetGoogleSearch = False
campaign.networkSetting.targetSearchNetwork = False
campaign.networkSetting.targetContentNetwork = True
campaign.networkSetting.targetPartnerSearchNetwork = False
' Set real time bidding settings.
Dim rtbSetting As New RealTimeBiddingSetting
rtbSetting.optIn = True
campaign.settings = New Setting() {rtbSetting}
' Optional: Set the start date.
campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd")
' Optional: Set the end date.
campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd")
' Optional: Set the frequency cap.
Dim frequencyCap As New FrequencyCap
frequencyCap.impressions = 5
frequencyCap.level = Level.ADGROUP
frequencyCap.timeUnit = TimeUnit.DAY
campaign.frequencyCap = frequencyCap
' Create the operation.
Dim operation As New CampaignOperation
operation.operator = [Operator].ADD
operation.operand = campaign
operations.Add(operation)
Next
Try
' Add the campaign.
Dim retVal As CampaignReturnValue = campaignService.mutate(operations.ToArray())
' Display the results.
If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) AndAlso _
(retVal.value.Length > 0)) Then
For Each newCampaign As Campaign In retVal.value
Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.", _
newCampaign.name, newCampaign.id)
Next
Else
Console.WriteLine("No campaigns were added.")
End If
Catch ex As Exception
Console.WriteLine("Failed to add campaigns. Exception says ""{0}""", ex.Message)
End Try
End Sub
End Class
End Namespace
|
stevemanderson/googleads-dotnet-lib
|
examples/AdXBuyer/Vb/v201502/BasicOperations/AddCampaigns.vb
|
Visual Basic
|
apache-2.0
| 6,206
|
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates
Imports Aspose.Email.Imap
'
'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
'when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
'If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
'install it and then add its reference to this project. For any issues, questions or suggestions
'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
'
Namespace Aspose.Email.Examples.VisualBasic.Email.Exchange
Class ExchangeServerUsesSSL
' ExStart:ExchangeServerUsesSSL
Public Shared Sub Run()
' Connect to Exchange Server using ImapClient class
Dim imapClient As New ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", New RemoteCertificateValidationCallback(AddressOf RemoteCertificateValidationHandler))
imapClient.SecurityOptions = SecurityOptions.SSLExplicit
' Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox)
' Get the list of messages
Dim msgCollection As ImapMessageInfoCollection = imapClient.ListMessages()
For Each msgInfo As ImapMessageInfo In msgCollection
Console.WriteLine(msgInfo.Subject)
Next
' Disconnect from the server
imapClient.Dispose()
End Sub
' Certificate verification handler
Private Shared Function RemoteCertificateValidationHandler(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
Return True
' ignore the checks and go ahead
End Function
' ExEnd:ExchangeServerUsesSSL
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Email-for-.NET
|
Examples/VisualBasic/Exchange/ExchangeServerUsesSSL.vb
|
Visual Basic
|
mit
| 1,774
|
#Region "Imported Namespaces"
Imports System
Imports System.Collections.Generic
Imports Autodesk.Revit.ApplicationServices
Imports Autodesk.Revit.Attributes
Imports Autodesk.Revit.DB
Imports Autodesk.Revit.UI
Imports Autodesk.Revit.UI.Selection
#End Region
<Transaction(TransactionMode.Manual)>
Public Class AdskCommand
Implements IExternalCommand
''' <summary>
''' The one and only method required by the IExternalCommand interface, the main entry point for every external command.
''' </summary>
''' <param name="commandData">Input argument providing access to the Revit application, its documents and their properties.</param>
''' <param name="message">Return argument to display a message to the user in case of error if Result is not Succeeded.</param>
''' <param name="elements">Return argument to highlight elements on the graphics screen if Result is not Succeeded.</param>
''' <returns>Cancelled, Failed or Succeeded Result code.</returns>
Public Function Execute(
ByVal commandData As ExternalCommandData,
ByRef message As String,
ByVal elements As ElementSet) _
As Result Implements IExternalCommand.Execute
Dim uiapp As UIApplication = commandData.Application
Dim uidoc As UIDocument = uiapp.ActiveUIDocument
Dim app As Application = uiapp.Application
Dim doc As Document = uidoc.Document
Dim sel As Selection = uidoc.Selection
'TODO: Add your code here
Using tx As New Transaction(doc)
tx.Start("$projectname$")
tx.Commit()
End Using
'Must return some code
Return Result.Succeeded
End Function
End Class
|
jeremytammik/VisualStudioRevitAddinWizard
|
vb/AdskCommand.vb
|
Visual Basic
|
mit
| 1,655
|
Imports System.Collections.ObjectModel
Namespace Areas.HelpPage.ModelDescriptions
Public Class ComplexTypeModelDescription
Inherits ModelDescription
Private _properties As Collection(Of ParameterDescription)
Public Sub New()
Properties = New Collection(Of ParameterDescription)()
End Sub
Public Property Properties() As Collection(Of ParameterDescription)
Get
Return _properties
End Get
Private Set(value As Collection(Of ParameterDescription))
_properties = value
End Set
End Property
End Class
End Namespace
|
Terminator-Aaron/Katana
|
aspnetwebsrc/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.vb
|
Visual Basic
|
apache-2.0
| 663
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Imports Microsoft.CodeAnalysis.Snippets
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion
Public Class VisualBasicCompletionSnippetNoteTests
Private _markup As XElement = <document>
<![CDATA[Imports System
Class Foo
$$
End Class]]></document>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteAddedToDescription_ExactMatch() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "Interface").ConfigureAwait(True)
state.SendTypeChars("Interfac")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Keyword, "Interface") & vbCrLf &
VBFeaturesResources.InterfaceKeywordToolTip & vbCrLf &
String.Format(FeaturesResources.NoteTabTwiceToInsertTheSnippet, "Interface")).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteAddedToDescription_DifferentSnippetShortcutCasing() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "intErfaCE").ConfigureAwait(True)
state.SendTypeChars("Interfac")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Keyword, "Interface") & vbCrLf &
VBFeaturesResources.InterfaceKeywordToolTip & vbCrLf &
String.Format(FeaturesResources.NoteTabTwiceToInsertTheSnippet, "Interface")).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSubstringOfInsertedText() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "Interfac").ConfigureAwait(True)
state.SendTypeChars("Interfac")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Keyword, "Interface") & vbCrLf &
VBFeaturesResources.InterfaceKeywordToolTip).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSuperstringOfInsertedText() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "Interfaces").ConfigureAwait(True)
state.SendTypeChars("Interfac")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Keyword, "Interface") & vbCrLf &
VBFeaturesResources.InterfaceKeywordToolTip).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteNotAddedToDescription_DisplayTextMatchesShortcutButInsertionTextDoesNot() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "DisplayText").ConfigureAwait(True)
state.SendTypeChars("DisplayTex")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:="").ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteAddedToDescription_DisplayTextDoesNotMatchShortcutButInsertionTextDoes() As Task
Using state = Await CreateVisualBasicSnippetExpansionNoteTestState(_markup, "InsertionText").ConfigureAwait(True)
state.SendTypeChars("DisplayTex")
Await state.AssertCompletionSession().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.NoteTabTwiceToInsertTheSnippet, "InsertionText")).ConfigureAwait(True)
End Using
End Function
Private Async Function CreateVisualBasicSnippetExpansionNoteTestState(xElement As XElement, ParamArray snippetShortcuts As String()) As Task(Of TestState)
Dim state = TestState.CreateVisualBasicTestState(
xElement,
New CompletionListProvider() {New MockCompletionProvider(New TextSpan(31, 10))},
Nothing,
New List(Of Type) From {GetType(TestVisualBasicSnippetInfoService)})
Dim testSnippetInfoService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService(Of ISnippetInfoService)(), TestVisualBasicSnippetInfoService)
Await testSnippetInfoService.SetSnippetShortcuts(snippetShortcuts).ConfigureAwait(True)
Return state
End Function
End Class
End Namespace
|
Inverness/roslyn
|
src/VisualStudio/Core/Test/Completion/VisualBasicCompletionSnippetNoteTests.vb
|
Visual Basic
|
apache-2.0
| 5,827
|
' 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 System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ClsComplianceTests
Inherits BasicTestBase
<Fact>
Public Sub NoAssemblyLevelAttributeRequired()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
' In C#, an assembly-level attribute is required. In VB, that is not the case.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AssemblyLevelAttributeAllowed()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnPrivate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Outer
<CLSCompliant(True)>
Private Class A
End Class
<CLSCompliant(True)>
Friend Class B
End Class
<CLSCompliant(True)>
Protected Class C
End Class
<CLSCompliant(True)>
Friend Protected Class D
End Class
<CLSCompliant(True)>
Public Class E
End Class
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on members not visible outside the assembly.
' VB does not.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
Public Function M(<CLSCompliant(True)> x As Integer) As Integer
Return 0
End Function
Public ReadOnly Property P(<CLSCompliant(True)> x As Integer) As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on parameters. VB does not.
' C# also warns about putting the attribute on return types, but VB
' does not support the "return" attribute target.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Explicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Implicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly:CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Alternating()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
<CLSCompliant(False)>
Public Class B
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Class D
<CLSCompliant(True)>
Public Class E
End Class
End Class
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: class 'A.B.C' cannot be marked CLS-compliant because its containing type 'A.B' is not CLS-compliant.
Public Class C
~
BC40030: class 'A.B.C.D.E' cannot be marked CLS-compliant because its containing type 'A.B.C.D' is not CLS-compliant.
Public Class E
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Inherits Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class A
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2_OtherAssemblies()
Dim lib1Source =
<compilation name="lib1">
<file name="a.vb">
<![CDATA[
Public Class Bad1
End Class
]]>
</file>
</compilation>
Dim lib2Source =
<compilation name="lib2">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public Class Bad2
End Class
]]>
</file>
</compilation>
Dim lib3Source =
<compilation name="lib3">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad3
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A1
Inherits Bad1
End Class
Public Class A2
Inherits Bad2
End Class
Public Class A3
Inherits Bad3
End Class
]]>
</file>
</compilation>
Dim lib1Ref = CreateCompilationWithMscorlib(lib1Source).EmitToImageReference()
Dim lib2Ref = CreateCompilationWithMscorlib(lib2Source).EmitToImageReference()
Dim lib3Ref = CreateCompilationWithMscorlib(lib3Source).EmitToImageReference()
CreateCompilationWithMscorlibAndReferences(source, {lib1Ref, lib2Ref, lib3Ref}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A1' is not CLS-compliant because it derives from 'Bad1', which is not CLS-compliant.
Public Class A1
~~
BC40026: 'A2' is not CLS-compliant because it derives from 'Bad2', which is not CLS-compliant.
Public Class A2
~~
BC40026: 'A3' is not CLS-compliant because it derives from 'Bad3', which is not CLS-compliant.
Public Class A3
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Interface()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Inherits Bad
End Interface
Public Interface B
Inherits Bad, Good
End Interface
Public Interface C
Inherits Good, Bad
End Interface
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40029: 'A' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface A
~
BC40029: 'B' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface B
~
BC40029: 'C' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface C
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Class()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Implements Bad
End Class
Public Class B
Implements Bad, Good
End Class
Public Class C
Implements Good, Bad
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' Implemented interfaces are not required to be compliant - only inherited ones.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NonCLSMemberInCLSInterface1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Function M1() As Bad
<CLSCompliant(False)>
Sub M2()
End Interface
Public Interface Kinds
<CLSCompliant(False)>
Sub M()
<CLSCompliant(False)>
Property P()
<CLSCompliant(False)>
Event E As Action
End Interface
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Function M1() As Bad
~~
BC40033: Non CLS-compliant 'Sub M2()' is not allowed in a CLS-compliant interface.
Sub M2()
~~
BC40033: Non CLS-compliant 'Sub M()' is not allowed in a CLS-compliant interface.
Sub M()
~
BC40033: Non CLS-compliant 'Property P As Object' is not allowed in a CLS-compliant interface.
Property P()
~
BC40033: Non CLS-compliant 'Event E As Action' is not allowed in a CLS-compliant interface.
Event E As Action
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NonCLSMustOverrideInCLSType1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public MustInherit Class A
Public MustOverride Function M1() As Bad
<CLSCompliant(False)>
Public MustOverride Sub M2()
End Class
Public MustInherit Class Kinds
<CLSCompliant(False)>
Public MustOverride Sub M()
<CLSCompliant(False)>
Public MustOverride Property P()
' VB doesn't support generic events
Public MustInherit Class C
End Class
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public MustOverride Function M1() As Bad
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'A'.
Public MustOverride Sub M2()
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Sub M()
~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Property P()
~
]]></errors>)
End Sub
<Fact>
Public Sub AbstractInCompliant_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)> Public Interface IFace
<CLSCompliant(False)> Property Prop1() As Long
<CLSCompliant(False)> Function F2() As Integer
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
<CLSCompliant(False)> Sub Sub4()
End Interface
<CLSCompliant(True)> Public MustInherit Class QuiteCompliant
<CLSCompliant(False)> Public MustOverride Sub Sub1()
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
<CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Property Prop1() As Long
~~~~~
BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Function F2() As Integer
~~
BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
~~~
BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Sub Sub4()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Public MustOverride Sub Sub1()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_GenericConstraintNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
End Class
<CLSCompliant(False)>
Public Class C2(Of t As {Good, Bad}, u As {Bad, Good})
End Class
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
<CLSCompliant(False)>
Public Delegate Sub D2(Of t As {Good, Bad}, u As {Bad, Good})()
Public Class C
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
<CLSCompliant(False)>
Public Sub M2(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' NOTE: Dev11 squiggles the problematic constraint, but we don't have enough info.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_FieldNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds1
Public F1 As Bad
Private F2 As Bad
End Class
<CLSCompliant(False)>
Public Class Kinds2
Public F3 As Bad
Private F4 As Bad
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'F1' is not CLS-compliant.
Public F1 As Bad
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Method()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1() As Bad
Throw New Exception()
End Function
Public Function M2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function M3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function M4() As Bad()
Throw New Exception()
End Function
Public Function M5() As Bad()()
Throw New Exception()
End Function
Public Function M6() As Bad(,)
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1() As Bad
Throw New Exception()
End Function
Public Function N2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function N3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function N4() As Bad()
Throw New Exception()
End Function
Public Function N5() As Bad()()
Throw New Exception()
End Function
Public Function N6() As Bad(,)
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'M4' is not CLS-compliant.
Public Function M4() As Bad()
~~
BC40027: Return type of function 'M5' is not CLS-compliant.
Public Function M5() As Bad()()
~~
BC40027: Return type of function 'M6' is not CLS-compliant.
Public Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Property()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Property P1() As Bad
Public Property P2() As Generic(Of Bad)
Public Property P3() As Generic(Of Generic(Of Bad))
Public Property P4() As Bad()
Public Property P5() As Bad()()
Public Property P6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Property Q1() As Bad
Public Property Q2() As Generic(Of Bad)
Public Property Q3() As Generic(Of Generic(Of Bad))
Public Property Q4() As Bad()
Public Property Q5() As Bad()()
Public Property Q6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'P4' is not CLS-compliant.
Public Property P4() As Bad()
~~
BC40027: Return type of function 'P5' is not CLS-compliant.
Public Property P5() As Bad()()
~~
BC40027: Return type of function 'P6' is not CLS-compliant.
Public Property P6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Delegate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Delegate Function M1() As Bad
Public Delegate Function M2() As Generic(Of Bad)
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
Public Delegate Function M4() As Bad()
Public Delegate Function M5() As Bad()()
Public Delegate Function M6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Delegate Function N1() As Bad
Public Delegate Function N2() As Generic(Of Bad)
Public Delegate Function N3() As Generic(Of Generic(Of Bad))
Public Delegate Function N4() As Bad()
Public Delegate Function N5() As Bad()()
Public Delegate Function N6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M4() As Bad()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M5() As Bad()()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1(p As Bad)
Throw New Exception()
End Function
Public Function M2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function M3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function M4(p As Bad())
Throw New Exception()
End Function
Public Function M5(p As Bad()())
Throw New Exception()
End Function
Public Function M6(p As Bad(,))
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1(p As Bad)
Throw New Exception()
End Function
Public Function N2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function N3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function N4(p As Bad())
Throw New Exception()
End Function
Public Function N5(p As Bad()())
Throw New Exception()
End Function
Public Function N6(p As Bad(,))
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M1(p As Bad)
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2(p As Generic(Of Bad))
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3(p As Generic(Of Generic(Of Bad)))
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M4(p As Bad())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M5(p As Bad()())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M6(p As Bad(,))
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I1
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface I2
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x' is not CLS-compliant.
Sub M(x As Bad)
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Property P(x As Bad) As Integer
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Delegate Sub D(x As Bad)
~
]]></errors>)
End Sub
' From LegacyTest\CSharp\Source\csharp\Source\ClsCompliance\generics\Rule_E_01.cs
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ConstructedTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Protected Class N
End Class
' Not CLS-compliant since C(Of Integer).N is not accessible within C(Of T) in all languages.
Protected Sub M1(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M2(n As C(Of T).N)
End Sub
Protected Class N2
' Not CLS-compliant
Protected Sub M3(n As C(Of ULong).N)
End Sub
End Class
End Class
Public Class D
Inherits C(Of Long)
' Not CLS-compliant
Protected Sub M4(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M5(n As C(Of Long).N)
End Sub
End Class
]]>
</file>
</compilation>
' Dev11 produces error BC30508 for M1 and M3
' Dev11 produces error BC30389 for M4 and M5
' Roslyn dropped these errors (since they weren't helpful) and, instead, reports CLS warnings.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ProtectedContainer()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of T)
Protected Class C2(Of U)
Public Class C3(Of V)
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U))
End Sub
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U).C3(Of V))
End Sub
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithArrayParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class EmptyAttribute
Inherits Attribute
End Class
Public Class PublicAttribute
Inherits Attribute
' Not accessible
Friend Sub New()
End Sub
' Not compliant
<CLSCompliant(False)>
Public Sub New(x As Integer)
End Sub
' Array argument
Public Sub New(a As Integer(,))
End Sub
' Array argument
Public Sub New(ParamArray a As Char())
End Sub
End Class
Friend Class InternalAttribute
Inherits Attribute
' Not accessible
Public Sub New()
End Sub
End Class
<CLSCompliant(False)>
Public Class BadAttribute
Inherits Attribute
' Fine, since type isn't compliant.
Public Sub New(array As Integer())
End Sub
End Class
Public Class NotAnAttribute
' Fine, since not an attribute type.
Public Sub New(array As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# requires that compliant attributes have at least one
' accessible constructor with no attribute parameters.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithNonPredefinedParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(m As MyAttribute)
End Sub
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ArrayArgumentToAttribute()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class B
End Class
<InternalArray({1})>
Public Class C
End Class
<NamedArgument(O:={1})>
Public Class D
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class _A
End Class
Public Class B_
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_A' is not CLS-compliant.
Public Class _A
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds
Public Sub _M()
End Sub
Public Property _P As Integer
Public Event _E As _ND
Public _F As Integer
Public Class _NC
End Class
Public Interface _NI
End Interface
Public Structure _NS
End Structure
Public Delegate Sub _ND()
Private _Private As Integer
<CLSCompliant(False)>
Public _NonCompliant As Integer
End Class
Namespace _NS1
End Namespace
Namespace NS1._NS2
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Sub _M()
~~
BC40031: Name '_P' is not CLS-compliant.
Public Property _P As Integer
~~
BC40031: Name '_E' is not CLS-compliant.
Public Event _E As _ND
~~
BC40031: Name '_F' is not CLS-compliant.
Public _F As Integer
~~
BC40031: Name '_NC' is not CLS-compliant.
Public Class _NC
~~~
BC40031: Name '_NI' is not CLS-compliant.
Public Interface _NI
~~~
BC40031: Name '_NS' is not CLS-compliant.
Public Structure _NS
~~~
BC40031: Name '_ND' is not CLS-compliant.
Public Delegate Sub _ND()
~~~
BC40031: Name '_NS1' is not CLS-compliant.
Namespace _NS1
~~~~
BC40031: Name '_NS2' is not CLS-compliant.
Namespace NS1._NS2
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Overrides()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub _M()
End Sub
End Class
Public Class Derived
Inherits Base
Public Overrides Sub _M()
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# doesn't report this warning on overrides.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Overridable Sub _M()
~~
BC40031: Name '_M' is not CLS-compliant.
Public Overrides Sub _M()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_NotReferencable()
Dim il = <![CDATA[
.class public abstract auto ansi B
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public hidebysig newslot specialname abstract virtual
instance int32 _getter() cil managed
{
}
.property instance int32 P()
{
.get instance int32 B::_getter()
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Inherits B
Public Overrides ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(source, il)
comp.AssertNoDiagnostics()
Dim accessor = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of PropertySymbol)("P").GetMethod
Assert.True(accessor.MetadataName.StartsWith("_", StringComparison.Ordinal))
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Parameter()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class B
Public Sub M(_p As Integer)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_NoAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_DisagreesWithAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub DroppedAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
Dim validator = Function(expectAssemblyLevel As Boolean, expectModuleLevel As Boolean) _
Sub(m As ModuleSymbol)
Dim predicate = Function(attr As VisualBasicAttributeData) attr.AttributeClass.Name = "CLSCompliantAttribute"
If expectModuleLevel Then
AssertEx.Any(m.GetAttributes(), predicate)
Else
AssertEx.None(m.GetAttributes(), predicate)
End If
If expectAssemblyLevel Then
AssertEx.Any(m.ContainingAssembly.GetAttributes(), predicate)
ElseIf m.ContainingAssembly IsNot Nothing Then
AssertEx.None(m.ContainingAssembly.GetAttributes(), predicate)
End If
End Sub
CompileAndVerify(source, options:=TestOptions.ReleaseDll, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(True, False))
CompileAndVerify(source, options:=TestOptions.ReleaseModule, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(False, True), verify:=False) ' PEVerify doesn't like netmodules
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsAssembly()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
<Assembly: System.CLSCompliant(False)>
]]>
</file>
</compilation>
Dim moduleComp = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef = moduleComp.EmitToImageReference()
CreateCompilationWithMscorlibAndReferences(source, {moduleRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsModule()
Dim source =
<compilation name="A">
<file name="a.vb">
</file>
</compilation>
Dim moduleComp1 = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef1 = moduleComp1.EmitToImageReference()
Dim moduleComp2 = CreateCSharpCompilation("[assembly:System.CLSCompliant(false)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="B")
Dim moduleRef2 = moduleComp2.EmitToImageReference()
CreateCompilationWithMscorlibAndReferences(source, {moduleRef1, moduleRef2}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub AssemblyIgnoresModuleAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Module: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from module, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub ModuleIgnoresAssemblyAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from assembly, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source, OutputKind.NetModule).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub IgnoreModuleAttributeInReferencedAssembly()
Dim source =
<compilation name="A">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
]]></file>
</compilation>
Dim assemblyLevelLibSource = <![CDATA[
[assembly:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim moduleLevelLibSource = <![CDATA[
[module:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim assemblyLevelLibRef = CreateCSharpCompilation(assemblyLevelLibSource).EmitToImageReference()
Dim moduleLevelLibRef = CreateCSharpCompilation(moduleLevelLibSource).EmitToImageReference(Nothing) ' suppress warning
' Attribute respected.
CreateCompilationWithMscorlibAndReferences(source, {assemblyLevelLibRef}).AssertNoDiagnostics()
' Attribute not respected.
CreateCompilationWithMscorlibAndReferences(source, {moduleLevelLibRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EnumUnderlyingTypeNotCLS1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Enum E1 As UInteger
A
End Enum
Friend Enum E2 As UInteger
A
End Enum
<CLSCompliant(False)>
Friend Enum E3 As UInteger
A
End Enum
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant.
Public Enum E1 As UInteger
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_TypeNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad1
End Class
Public Class Bad2
End Class
Public Class BadGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Good
End Class
<CLSCompliant(True)>
Public Class GoodGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Test
' Reported within compliant generic types.
Public x1 As GoodGeneric(Of Good, Good) ' Fine
Public x2 As GoodGeneric(Of Good, Bad1)
Public x3 As GoodGeneric(Of Bad1, Good)
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
' Reported within non-compliant generic types.
Public Property y1 As BadGeneric(Of Good, Good)
Public Property y2 As BadGeneric(Of Good, Bad1)
Public Property y3 As BadGeneric(Of Bad1, Good)
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'Bad1' is not CLS-compliant.
Public x2 As GoodGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x3 As GoodGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40027: Return type of function 'y1' is not CLS-compliant.
Public Property y1 As BadGeneric(Of Good, Good)
~~
BC40027: Return type of function 'y2' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40027: Return type of function 'y3' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40027: Return type of function 'y4' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant1()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
]]>
</file>
</compilation>
' Nothing reported since the namespace inherits CLSCompliant(False) from the assembly.
CreateCompilationWithMscorlib(source1, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertNoDiagnostics()
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source2, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source3 =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class Test
End Class
]]>
</file>
</compilation>
Dim moduleRef = CreateCompilationWithMscorlib(source3, options:=TestOptions.ReleaseModule).EmitToImageReference()
CreateCompilationWithMscorlibAndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseDll.WithRootNamespace("_A").WithConcurrentBuild(False)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source4 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndReferences(source4, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A").WithConcurrentBuild(True)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlibAndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A")).AssertTheseDiagnostics()
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A._B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_B' in the root namespace 'A._B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_C' in the root namespace 'A.B._C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B._C' is not CLS-compliant.
BC40039: Name '_C' in the root namespace '_A.B._C' is not CLS-compliant.
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As Object = SByte.MaxValue,
Optional x01 As Object = Byte.MaxValue,
Optional x02 As Object = Short.MaxValue,
Optional x03 As Object = UShort.MaxValue,
Optional x04 As Object = Integer.MaxValue,
Optional x05 As Object = UInteger.MaxValue,
Optional x06 As Object = Long.MaxValue,
Optional x07 As Object = ULong.MaxValue,
Optional x08 As Object = Char.MaxValue,
Optional x09 As Object = True,
Optional x10 As Object = Single.MaxValue,
Optional x11 As Object = Double.MaxValue,
Optional x12 As Object = Decimal.MaxValue,
Optional x13 As Object = "ABC",
Optional x14 As Object = #1/1/2001#)
End Sub
End Class
]]>
</file>
</compilation>
' As in dev11, this only applies to int8, uint16, uint32, and uint64
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40042: Type of optional value for optional parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As Object = SByte.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x03' is not CLS-compliant.
Optional x03 As Object = UShort.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x05' is not CLS-compliant.
Optional x05 As Object = UInteger.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x07' is not CLS-compliant.
Optional x07 As Object = ULong.MaxValue,
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1_ParamterTypeNonCompliant()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_True()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Property P1 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(False)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
End Property
<CLSCompliant(False)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_False()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(True)>
Public Property P1 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(True)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
End Property
<CLSCompliant(True)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: See warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P2' is not CLS-compliant.
Public ReadOnly Property P2 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P3' is not CLS-compliant.
Public WriteOnly Property P3 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSEventMethodInNonCLSType3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class C
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
' NOTE: No warnings about RaiseEvent accessors.
' NOTE: CLSCompliant(False) on event doesn't suppress warnings.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40053: 'AddHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'AddHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub EventAccessors()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(True)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(False)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(False)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(False)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we do not warn that we are ignoring CLSCompliantAttribute on event accessors.
' NOTE: See warning about non-compliant type UInteger only for E2.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Custom Event E2 As Action(Of UInteger)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EventDelegateTypeNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace Q
<CLSCompliant(False)>
Public Delegate Sub Bad()
End Namespace
<CLSCompliant(True)>
Public Class C
Public Custom Event E1 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Event E2 As Q.Bad
Public Event E3(x As UInteger)
<CLSCompliant(False)>
Public Custom Event E4 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Event E5 As Q.Bad
<CLSCompliant(False)>
Public Event E6(x As UInteger)
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40050: Delegate type 'Bad' of event 'E1' is not CLS-compliant.
Public Custom Event E1 As Q.Bad
~~
BC40050: Delegate type 'Bad' of event 'E2' is not CLS-compliant.
Public Event E2 As Q.Bad
~~
BC40028: Type of parameter 'x' is not CLS-compliant.
Public Event E3(x As UInteger)
~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeTrue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeFalse()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub NonCompliantInaccessible()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Private Function M(b As Bad) As Bad
Return b
End Function
Private Property P(b As Bad) As Bad
Get
Return b
End Get
Set(value As Bad)
End Set
End Property
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub NonCompliantAbstractInNonCompliantType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public MustInherit Class Bad
Public MustOverride Function M(b As Bad) As Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub SpecialTypes()
Dim sourceTemplate = <![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As {0})
End Sub
End Class
]]>.Value.Replace(vbCr, vbCrLf)
Dim helper = CreateCompilationWithMscorlib({""}, Nothing)
Dim integerType = helper.GetSpecialType(SpecialType.System_Int32)
For Each st As SpecialType In [Enum].GetValues(GetType(SpecialType))
Select Case (st)
Case SpecialType.None, SpecialType.System_Void, SpecialType.System_Runtime_CompilerServices_IsVolatile
Continue For
End Select
Dim type = helper.GetSpecialType(st)
If type.Arity > 0 Then
type = type.Construct(ArrayBuilder(Of TypeSymbol).GetInstance(type.Arity, integerType).ToImmutableAndFree())
End If
Dim qualifiedName = type.ToTestDisplayString()
Dim source = String.Format(sourceTemplate, qualifiedName)
Dim comp = CreateCompilationWithMscorlib({source}, Nothing)
Select Case (st)
Case SpecialType.System_SByte, SpecialType.System_UInt16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UIntPtr, SpecialType.System_TypedReference
Assert.Equal(ERRID.WRN_ParamNotCLSCompliant1, DirectCast(comp.GetDeclarationDiagnostics().Single().Code, ERRID))
End Select
Next
End Sub
<WorkItem(697178, "DevDiv")>
<Fact>
Public Sub ConstructedSpecialTypes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As IEnumerable(Of UInteger))
End Sub
End Class
]]>
</file>
</compilation>
' Native C# misses this diagnostic
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Sub M(p As IEnumerable(Of UInteger))
~
]]></errors>)
End Sub
<Fact>
Public Sub MissingAttributeType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Missing>
Public Class C
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'Missing' is not defined.
<Missing>
~~~~~~~
]]></errors>)
End Sub
<WorkItem(709317, "DevDiv")>
<Fact>
Public Sub Repro709317()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class D
Public Function M() As C
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim libRef = CreateCompilationWithMscorlib(libSource).EmitToImageReference()
Dim comp = CreateCompilationWithMscorlibAndReferences(source, {libRef})
Dim tree = comp.SyntaxTrees.Single()
comp.GetDiagnosticsForTree(CompilationStage.Declare, tree, filterSpanWithinTree:=Nothing, includeEarlierStages:=True)
End Sub
<WorkItem(709317, "DevDiv")>
<Fact>
Public Sub FilterTree()
Dim sourceTemplate = <![CDATA[
Imports System
Namespace N{0}
<CLSCompliant(False)>
Public Class NonCompliant
End Class
<CLSCompliant(False)>
Public Interface INonCompliant
End Interface
<CLSCompliant(True)>
Public Class Compliant
Inherits NonCompliant
Implements INonCompliant
Public Function M(Of T As NonCompliant)(n As NonCompliant)
Throw New Exception
End Function
Public F As NonCompliant
Public Property P As NonCompliant
End Class
End Namespace
]]>.Value.Replace(vbCr, vbCrLf)
Dim tree1 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 1), path:="a.vb")
Dim tree2 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 2), path:="b.vb")
Dim comp = CreateCompilationWithMscorlib({tree1, tree2}, TestOptions.ReleaseDll)
' Two copies of each diagnostic - one from each file.
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
CompilationUtils.AssertTheseDiagnostics(comp.GetDiagnosticsForTree(CompilationStage.Declare, tree1, filterSpanWithinTree:=Nothing, includeEarlierStages:=False),
<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
End Sub
<WorkItem(718503, "DevDiv")>
<Fact>
Public Sub ErrorTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Implements IError
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'IError' is not defined.
Implements IError
~~~~~~
]]></errors>)
End Sub
' Make sure nothing blows up when a protected symbol has no containing type.
<Fact>
Public Sub ProtectedTopLevelType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Protected Class C
Public F As UInteger
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Class C
~
]]></errors>)
End Sub
<Fact>
Public Sub ProtectedMemberOfSealedType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public NotInheritable Class C
Protected F As UInteger ' No warning, since not accessible outside assembly.
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub InheritedCompliance1()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<CLSCompliant(True)>
Public Class Base
End Class
Public Class Derived
Inherits Base
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we ignore the fact that Derived inherits CLSCompliant(True) from Base.
Dim libRef = CreateCompilationWithMscorlib(libSource).EmitToImageReference()
CreateCompilationWithMscorlibAndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub InheritedCompliance2()
Dim il = <![CDATA[.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
}
.module a.dll
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(false)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit Derived
extends Base
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we consider the fact that Derived inherits CLSCompliant(False) from Base
' (since it is not from the current assembly).
Dim libRef = CompileIL(il.Value, appendDefaultHeader:=False)
CreateCompilationWithMscorlibAndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'B' is not CLS-compliant.
Public B as Base
~
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub AllAttributeConstructorsRequireArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(a As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithArrayArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
<Array({1})>
<Params(1)>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithNonCompliantyArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_ArrayRank()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) 'BC40035
End Sub
Public Sub M2(x As Integer(,,))
End Sub
Public Sub M2(x As Integer(,)) 'BC40035
End Sub
Public Sub M3(x As Integer())
End Sub
Private Sub M3(x As Integer(,)) ' Fine, since inaccessible.
End Sub
Public Sub M4(x As Integer())
End Sub
<CLSCompliant(False)>
Private Sub M4(x As Integer(,)) ' Fine, since flagged.
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M1(x As Integer())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Integer(,)) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer(*,*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer(,)) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_RefKind()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(ByRef x As Integer()) 'BC30345
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: Illegal, even without compliance checking.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30345: 'Public Sub M1(x As Integer())' and 'Public Sub M1(ByRef x As Integer())' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public Sub M1(x As Integer())
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_ArrayOfArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) 'BC40035
End Sub
Public Sub M2(x As Integer()()())
End Sub
Public Sub M2(x As Integer()()) 'BC40035
End Sub
Public Sub M3(x As Integer()())
End Sub
Public Sub M3(x As Integer()) 'Fine (C# warns)
End Sub
Public Sub M4(x As Integer(,)(,))
End Sub
Public Sub M4(x As Integer()(,)) 'BC40035
End Sub
Public Sub M5(x As Integer(,)(,))
End Sub
Public Sub M5(x As Integer(,)()) 'BC40035
End Sub
Public Sub M6(x As Long()())
End Sub
Private Sub M6(x As Char()()) ' Fine, since inaccessible.
End Sub
Public Sub M7(x As Long()())
End Sub
<CLSCompliant(False)>
Public Sub M7(x As Char()()) ' Fine, since tagged (dev11 reports BC40035)
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Char()())' is not CLS-compliant because it overloads 'Public Sub M1(x As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Char()()) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer()())' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer()()) 'BC40035
~~
BC40035: 'Public Sub M4(x As Integer()(*,*))' is not CLS-compliant because it overloads 'Public Sub M4(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M4(x As Integer()(,)) 'BC40035
~~
BC40035: 'Public Sub M5(x As Integer(*,*)())' is not CLS-compliant because it overloads 'Public Sub M5(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M5(x As Integer(,)()) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Properties()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Property P1(x As Long()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P1(x As Char()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String(,)) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Property P1(x As Char()()) As Integer' is not CLS-compliant because it overloads 'Public Property P1(x As Long()()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P1(x As Char()()) As Integer
~~
BC40035: 'Public Property P2(x As String(*,*)) As Integer' is not CLS-compliant because it overloads 'Public Property P2(x As String()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P2(x As String(,)) As Integer
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_MethodKinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub New(p As Long()())
End Sub
Public Sub New(p As Char()())
End Sub
Public Shared Widening Operator CType(p As Long()) As C
Return Nothing
End Operator
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,,)) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
' Static constructors can't be overloaded
' Destructors can't be overloaded.
' Accessors are tested separately.
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for operators.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub New(p As Char()())' is not CLS-compliant because it overloads 'Public Sub New(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub New(p As Char()())
~~~
BC40035: 'Public Shared Widening Operator CType(p As Long(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Widening Operator CType(p As Long()) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
~~~~~
BC40035: 'Public Shared Narrowing Operator CType(p As String(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Narrowing Operator CType(p As String(*,*,*)) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Operators()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Shared Widening Operator CType(p As C) As Integer
Return Nothing
End Operator
Public Shared Widening Operator CType(p As C) As Long
Return Nothing
End Operator
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_TypeParameterArray()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Public Sub M1(t As T())
End Sub
Public Sub M1(t As Integer())
End Sub
Public Sub M2(Of U)(t As U())
End Sub
Public Sub M2(Of U)(t As Integer())
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_InterfaceMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I
Sub M(p As Long()())
End Interface
Public Class ImplementWithSameName
Implements I
Public Sub M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
End Sub
End Class
Public Class ImplementWithOtherName
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As String) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Base
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
End Class
Public Class Derived1
Inherits Base
Implements I
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Derived2
Inherits Base
Public Sub M(p()() As Short) 'Mimic (C#) dev11 bug - don't report conflict with interface member.
End Sub
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for interface members.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As String()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As String) 'BC40035 (roslyn only)
~
BC40035: 'Public Sub M(p As Boolean()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_BaseMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub M(p As Long()())
End Sub
Public Overridable WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Overload
Inherits Base
Public Overloads Sub M(p As Char()())
End Sub
Public Overloads WriteOnly Property P(q As Char()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Hide
Inherits Base
Public Shadows Sub M(p As Long()())
End Sub
Public Shadows WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Override
Inherits Base
Public Overrides Sub M(p As Long()())
End Sub
Public Overrides WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived1
Inherits Base
End Class
Public Class Derived2
Inherits Derived1
Public Overloads Sub M(p As String()())
End Sub
Public Overloads WriteOnly Property P(q As String()())
Set(value)
End Set
End Property
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for base type members.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Overloads Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As Char()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As Char()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As Char()())
~
BC40035: 'Public Overloads Sub M(p As String()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As String()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As String()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As String()())
~
]]></errors>)
End Sub
<Fact>
Public Sub WithEventsWarning()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public WithEvents F As Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
' Make sure we don't produce a bunch of spurious warnings for synthesized members.
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'F' is not CLS-compliant.
Public WithEvents F As Bad
~
]]></errors>)
End Sub
<WorkItem(749432, "DevDiv")>
<Fact>
Public Sub InvalidAttributeArgument()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Module VBCoreHelperFunctionality
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As SByte) As Integer
Return (New With {.anonymousField = 1}).anonymousField
End Function
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As UInt16) As Integer
Return (New With {.anonymousField = 2}).anonymousField
End Function
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(749352, "DevDiv")>
<Fact>
Public Sub Repro749352()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace ClsCompClass001f
<CLSCompliant(False)>
Public Class ContainerClass
'COMPILEWARNING: BC40030, "Scen6"
<CLSCompliant(True)>
Public Event Scen6(ByVal x As Integer)
End Class
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: event 'Public Event Scen6(x As Integer)' cannot be marked CLS-compliant because its containing type 'ContainerClass' is not CLS-compliant.
Public Event Scen6(ByVal x As Integer)
~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(1026453, "DevDiv")>
Public Sub Bug1026453()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Namespace N1
Public Class A
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib(source1, TestOptions.ReleaseModule)
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
Namespace N1
Public Class B
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp2 = CreateCompilationWithMscorlibAndReferences(source2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll.WithConcurrentBuild(False))
comp2.AssertNoDiagnostics()
comp2.WithOptions(TestOptions.ReleaseDll.WithConcurrentBuild(True)).AssertNoDiagnostics()
Dim comp3 = comp2.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(False))
comp3.AssertNoDiagnostics()
comp3.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(True)).AssertNoDiagnostics()
End Sub
End Class
End Namespace
|
wschae/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ClsComplianceTests.vb
|
Visual Basic
|
apache-2.0
| 108,545
|
' 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.VisualStudio.GraphModel
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Friend Class MockGraphContext
Implements IGraphContext
Private ReadOnly _direction As GraphContextDirection
Private ReadOnly _graph As Graph
Private ReadOnly _inputNodes As ISet(Of GraphNode)
Private ReadOnly _outputNodes As New HashSet(Of GraphNode)
Public Sub New(direction As GraphContextDirection, graph As Graph, inputNodes As IEnumerable(Of GraphNode))
_direction = direction
_graph = graph
_inputNodes = New HashSet(Of GraphNode)(inputNodes)
End Sub
Public Event Canceled(sender As Object, e As EventArgs) Implements IGraphContext.Canceled
Public ReadOnly Property CancelToken As CancellationToken Implements IGraphContext.CancelToken
Get
End Get
End Property
Public Event Completed(sender As Object, e As EventArgs) Implements IGraphContext.Completed
Public ReadOnly Property Direction As GraphContextDirection Implements IGraphContext.Direction
Get
Return _direction
End Get
End Property
Public ReadOnly Property Errors As IEnumerable(Of Exception) Implements IGraphContext.Errors
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetValue(Of T)(name As String) As T Implements IGraphContext.GetValue
Return Nothing
End Function
Public Property Graph As Graph Implements IGraphContext.Graph
Get
Return _graph
End Get
Set(value As Graph)
Throw New NotImplementedException()
End Set
End Property
Public Function HasValue(name As String) As Boolean Implements IGraphContext.HasValue
Return False
End Function
Public ReadOnly Property InputNodes As ISet(Of GraphNode) Implements IGraphContext.InputNodes
Get
Return _inputNodes
End Get
End Property
Public ReadOnly Property LinkCategories As IEnumerable(Of GraphCategory) Implements IGraphContext.LinkCategories
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property LinkDepth As Integer Implements IGraphContext.LinkDepth
Get
Return 1
End Get
End Property
Public ReadOnly Property NodeCategories As IEnumerable(Of GraphCategory) Implements IGraphContext.NodeCategories
Get
Throw New NotImplementedException()
End Get
End Property
Public Sub OnCompleted() Implements IGraphContext.OnCompleted
End Sub
Public ReadOnly Property OutputNodes As ISet(Of GraphNode) Implements IGraphContext.OutputNodes
Get
Return _outputNodes
End Get
End Property
Public Sub ReportError(exception As Exception) Implements IGraphContext.ReportError
End Sub
Public Sub ReportProgress(current As Integer, maximum As Integer, message As String) Implements IGraphContext.ReportProgress
End Sub
Public ReadOnly Property RequestedProperties As IEnumerable(Of GraphProperty) Implements IGraphContext.RequestedProperties
Get
Throw New NotImplementedException()
End Get
End Property
Public Sub SetValue(Of T)(name As String, value As T) Implements IGraphContext.SetValue
End Sub
Public ReadOnly Property TrackChanges As Boolean Implements IGraphContext.TrackChanges
Get
Return False
End Get
End Property
End Class
End Namespace
|
physhi/roslyn
|
src/VisualStudio/Core/Test/Progression/MockGraphContext.vb
|
Visual Basic
|
apache-2.0
| 4,155
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic
Public Class DeclarationConflictTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFields()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Dim [|$$foo|] As Integer
Dim {|Conflict:bar|} As Integer
End Module
</Document>
</Project>
</Workspace>, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFieldAndMethod()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Dim [|$$foo|] As Integer
Sub {|Conflict:bar|}()
End Module
</Document>
</Project>
</Workspace>,
renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoMethodsWithSameSignature()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Sub [|$$foo|]()
End Sub
Sub {|Conflict:bar|}()
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoParameters()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Sub f([|$$foo|] As Integer, {|Conflict:bar|} As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsWithDifferentSignatures()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module FooModule
Sub [|$$foo|]()
End Sub
Sub bar(parameter As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="bar")
End Using
End Sub
<Fact>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoLocals()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim {|stmt1:$$i|} = 1
Dim {|Conflict:j|} = 2
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLocalAndParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim {|stmt1:$$i|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenQueryVariableAndParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim z = From {|stmt1:$$x|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoQueryVariables()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim z = From {|Conflict:x|} In args
From {|stmt1:$$y|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInsideMethod()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Sub Main()
Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="c")
result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInFieldInitializer()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c)
End Module
</Document>
</Project>
</Workspace>, renameTo:="c")
result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenLambdaParameterAndField()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|fieldinit:$$c|}) Exit Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabels()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Program
Sub Main()
{|Conflict:Foo|}:
[|$$Bar|]:
Dim f = Sub()
Foo:
End Sub
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByByRef()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$c|](ByRef x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByOptional()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsDifferingByArity()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub a(Of T)(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="a")
End Using
End Sub
<Fact>
<WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Module Program
Sub Main()
__ = {|Conflict1:$$Google|}
{|Conflict2:Google|} = __
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Microsoft")
result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim q = From i In a
Where i Mod 2 = 0
Select Function() i * i
For Each {|Conflict:$$sq|} In q
Console.Write({|Conflict:sq|}())
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="Write")
result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenAliases()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports A = X.Something
Imports {|Conflict:$$B|} = X.SomethingElse
Namespace X
Class Something
End Class
Class SomethingElse
End Class
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitVariableAndClass()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Class X
End Class
Module M
Sub Main()
{|conflict:$$Y|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="X")
result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedAlias()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [|$$A|] = NS1.Something
Imports {|conflict1:Something|} = NS1
Namespace NS1
Class Something
Public Something()
End Class
End Namespace
Class Program
Dim a As {|noconflict:A|}
Dim q As {|conflict2:Something|}.{|conflict3:Something|}
End Class
</Document>
</Project>
</Workspace>, renameTo:="Something")
result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class B
Inherits A
Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class C
Inherits A
Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, renameTo:="X")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module [|$$M|] ' Rename M to X
Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x)
End Module
</Document>
</Project>
</Workspace>, renameTo:="X")
result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
For Each {|conflict:x|} In ""
Next
End Sub
End Module
End Namespace
Namespace X
Class [|$$X|] ' Rename X to M
End Class
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="M")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:foo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:foo|}} Select g).First()
Console.WriteLine({|stmt:$$foo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:foo|} As Integer In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:foo|}} Select g).First()
Console.WriteLine({|stmt:$$foo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Dim {|stmt1:foo|} as Integer
For Each {|ctrlvar:foo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:foo|}} Select g).First()
Console.WriteLine({|stmt2:$$foo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="g")
result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Public [|foo|] as Integer
Sub Main
For Each Program.{|ctrlvar:foo|} In {1, 2, 3}
Dim y As Integer = (From g In {{|query:foo|}} Select g).First()
Console.WriteLine({|stmt:$$foo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object()
Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First()
Console.WriteLine({|stmt:$$v1|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="c")
result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Select c).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="v4")
result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact(Skip:="657210")>
<WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_3()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="d")
result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForCatchVariable_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Try
Catch {|catchstmt:$$x|} as Exception
dim {|declconflict:y|} = 23
End Try
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo(Of {|declconflict:T|} as {New}, [|$$U|])
End Class
</Document>
</Project>
</Workspace>, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo
Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo
Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo(Of {|declconflict:[T]|})
Public Sub [|$$M|]()
End Sub
End Class
</Document>
</Project>
</Workspace>, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo(Of {|declconflict:[T]|})
Public [|$$M|] as Integer = 23
End Class
</Document>
</Project>
</Workspace>, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Linq
Module Program
Sub Main(args As String())
For Each {|stmt1:foo|} In {1, 2, 3}
Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:foo|}} Select g).First()
Console.WriteLine({|stmt2:$$foo|})
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, renameTo:="[g]")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")>
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
For Each x In New C()
Next
End Sub
Public Sub {|possibleImplicitConflict:$$Foo|}() ' Rename Foo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, renameTo:="movenext")
result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_1()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><() ' Rename Foo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, renameTo:="movenext")
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_2()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext(of T)() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
End Sub
Public Sub [|$$Foo|]() ' Rename Foo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, renameTo:="movenext")
End Using
End Sub
<WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")>
<Fact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictInsideSimpleArgument()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.ComponentModel
Imports System.Reflection
Class C
Const {|first:$$M|} As MemberTypes = MemberTypes.Method
Delegate Sub D(<DefaultValue({|second:M|})> x As Object);
End Class
</Document>
</Project>
</Workspace>, renameTo:="Method")
result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
End Class
End Namespace
|
amcasey/roslyn
|
src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb
|
Visual Basic
|
apache-2.0
| 43,174
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fOrdenes_Compras_Stratos"
'-------------------------------------------------------------------------------------------'
Partial Class fOrdenes_Compras_Stratos
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT Ordenes_Compras.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0) THEN Proveedores.Nom_Pro ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Ordenes_Compras.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE Ordenes_Compras.Nom_Pro END) END) AS Nom_Pro, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0) THEN Proveedores.Rif ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Ordenes_Compras.Rif = '') THEN Proveedores.Rif ELSE Ordenes_Compras.Rif END) END) AS Rif, ")
loComandoSeleccionar.AppendLine(" Proveedores.Nit, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0) THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (SUBSTRING(Ordenes_Compras.Dir_Fis,1, 200) = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE SUBSTRING(Ordenes_Compras.Dir_Fis,1, 200) END) END) AS Dir_Fis, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0) THEN Proveedores.Telefonos ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Ordenes_Compras.Telefonos = '') THEN Proveedores.Telefonos ELSE Ordenes_Compras.Telefonos END) END) AS Telefonos, ")
loComandoSeleccionar.AppendLine(" Proveedores.Fax, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Nom_Pro As Nom_Gen, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Rif As Rif_Gen, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Nit As Nit_Gen, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Dir_Fis As Dir_Gen, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Telefonos As Tel_Gen, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Cod_Uni, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Mon_Bru, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Mon_Des1, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Control, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Cod_Tra, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Mon_Rec1, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Por_Imp1, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Dis_Imp, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Mon_Imp1, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Mon_Net, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Cod_For, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Comentario, ")
loComandoSeleccionar.AppendLine(" Formas_Pagos.Nom_For, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Cod_Art, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Articulos.Generico = 0 THEN Articulos.Nom_Art")
loComandoSeleccionar.AppendLine(" ELSE Renglones_OCompras.Notas")
loComandoSeleccionar.AppendLine(" END AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Renglon, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Can_Art1, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Por_Des As Por_Des1, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Precio1 As Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Precio1 As Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Mon_Net As Neto, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Cod_Imp As Cod_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Por_Imp1 As Por_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_OCompras.Mon_Imp1 As Impuesto, ")
loComandoSeleccionar.AppendLine(" ISNULL(Unidades_Articulos.Can_Uni,Articulos.Can_Uni) AS Can_Uni ")
loComandoSeleccionar.AppendLine(" FROM Ordenes_Compras")
loComandoSeleccionar.AppendLine(" JOIN Renglones_OCompras ON (Ordenes_Compras.Documento = Renglones_OCompras.Documento)")
loComandoSeleccionar.AppendLine(" JOIN Proveedores ON (Ordenes_Compras.Cod_Pro = Proveedores.Cod_Pro)")
loComandoSeleccionar.AppendLine(" LEFT JOIN Formas_Pagos ON ( Ordenes_Compras.Cod_For = Formas_Pagos.Cod_For) ")
loComandoSeleccionar.AppendLine(" LEFT JOIN Articulos ON (Articulos.Cod_Art = Renglones_OCompras.Cod_Art) ")
loComandoSeleccionar.AppendLine(" LEFT JOIN Vendedores ON (Ordenes_Compras.Cod_Ven = Vendedores.Cod_Ven) ")
loComandoSeleccionar.AppendLine(" LEFT JOIN Unidades_Articulos ON (Renglones_OCompras.Cod_Art = Unidades_Articulos.Cod_Art)")
loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fOrdenes_Compras_Stratos", laDatosReporte)
'CType(loObjetoReporte.ReportDefinition.ReportObjects("Text25"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfOrdenes_Compras_Stratos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' CMS: 08/11/08: Programacion inicial '
'-------------------------------------------------------------------------------------------'
' RJG: 23/04/10: Corrección ortográfica. Eliminada dirección de la empresa bajo el logo. '
' Cambiada columna "Discount" por "Units/Case". '
'-------------------------------------------------------------------------------------------'
' MAT: 08/04/11: Ajuste del Select y de la vista de diseño '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fOrdenes_Compras_Stratos.aspx.vb
|
Visual Basic
|
mit
| 10,008
|
#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 PositionEndParser
Inherits ParserBase
Implements IParser
Private Const ModuleName As String = NameOf(PositionEndParser)
Friend Overrides Function ParseAsync(pVersion As Integer, timestamp As Date) As Task(Of Boolean)
LogSocketInputMessage(ModuleName, "ParseAsync")
_EventConsumers.AccountDataConsumer?.EndPosition(EventArgs.Empty)
Return Task.FromResult(Of Boolean)(True)
End Function
Friend Overrides ReadOnly Property MessageType As ApiSocketInMsgType
Get
Return ApiSocketInMsgType.PositionEnd
End Get
End Property
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/Parsers/PositionEndParser.vb
|
Visual Basic
|
mit
| 1,861
|
Imports System.IO
Imports System.Runtime.InteropServices
Module Example
<STAThread()> _
Sub Main()
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objPartDocument As SolidEdgePart.PartDocument = Nothing
Dim objStudyOwner As SolidEdgePart.StudyOwner = Nothing
Dim objStudy As SolidEdgePart.Study = Nothing
Dim objThermalStudy As SolidEdgePart.Study = Nothing
Dim objLoadOwner As SolidEdgePart.LoadOwner = Nothing
Dim objModels As SolidEdgePart.Models = Nothing
Dim objModel As SolidEdgePart.Model = Nothing
Dim objModelBody As SolidEdgeGeometry.Body = Nothing
Dim objGeomArray(0) As Object
Dim estudyType As SolidEdgePart.FEAStudyTypeEnum_Auto
Dim eMeshType As SolidEdgePart.FEAMeshTypeEnum_Auto
Dim dThickness As Double = 0
Dim dwInputOptions As UInteger = 0
Dim ulNumModes As ULong = 7
Dim dFreqlow As Double = 0
Dim dFreqHigh As Double = 1.0
Dim cmdLineOpts As String = ""
Dim nastranKeywordOpts As String = ""
Dim dwResultoptions As UInteger = 0
'Thermal Options
Dim dConvectionExp As Double = 0
Dim dEnclosureAmbientEle As Double = 0
Dim dwThrmlOptions As UInteger = 0
Try
OleMessageFilter.Register()
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objPartDocument = objApplication.ActiveDocument
' Get Study Owner
objStudyOwner = objPartDocument.StudyOwner
'Add Thermal Study
estudyType = SolidEdgePart.FEAStudyTypeEnum_Auto.eStudyTypeSSHT_Auto
eMeshType = SolidEdgePart.FEAMeshTypeEnum_Auto.eMeshTypeTetrahedral_Auto
objStudyOwner.AddThermalStudy(estudyType,
eMeshType,
dThickness,
dwInputOptions,
ulNumModes,
dFreqlow,
dFreqHigh,
cmdLineOpts,
nastranKeywordOpts,
dwResultoptions,
dwThrmlOptions,
dEnclosureAmbientEle,
dConvectionExp,
objStudy)
objThermalStudy = objStudy
objModels = objPartDocument.Models
objModel = objModels.Item(1)
' Get the study geometries
objModelBody = objModel.Body()
objGeomArray(0) = Nothing
objGeomArray(0) = objModelBody
' Deselect the geometry from study
objThermalStudy.SetGeometries(objGeomArray)
objThermalStudy.GetLoadOwner(objLoadOwner)
'Get Thermal Options
objThermalStudy.GetThermalStudyOptions(dwThrmlOptions, dEnclosureAmbientEle, dConvectionExp)
dEnclosureAmbientEle = 10
dConvectionExp = 3.4
'Set Thermal Options
objThermalStudy.SetThermalStudyOptions(dwThrmlOptions, dEnclosureAmbientEle, dConvectionExp)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
OleMessageFilter.Revoke()
End Try
End Sub
End Module
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.Study.SetThermalStudyOptions.vb
|
Visual Basic
|
mit
| 3,503
|
Imports System
Imports System.Net
Imports Independentsoft.Exchange
Namespace Sample
Class Module1
Shared Sub Main(ByVal args As String())
Dim credential As New NetworkCredential("username", "password")
Dim service As New Service("https://myserver/ews/Exchange.asmx", credential)
Try
Dim restriction As New IsEqualTo(AppointmentPropertyPath.Subject, "Meeting")
Dim findItemResponse As FindItemResponse = service.FindItem(StandardFolder.Calendar, restriction)
Dim startTimeProperty As New [Property](AppointmentPropertyPath.StartTime, DateTime.Today.AddHours(17))
Dim endTimeProperty As New [Property](AppointmentPropertyPath.EndTime, DateTime.Today.AddHours(20))
Dim properties As New List(Of [Property])()
properties.Add(startTimeProperty)
properties.Add(endTimeProperty)
If findItemResponse.Items.Count = 1 Then
Dim itemId As ItemId = findItemResponse.Items(0).ItemId
itemId = service.UpdateItem(itemId, properties, SendMeetingOption.SendToAllAndSaveCopy)
End If
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/VBSendMeetingUpdate1/Module1.vb
|
Visual Basic
|
mit
| 1,596
|
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Csla
Imports Csla.Data
Namespace Invoices.Business
''' <summary>
''' ProductTypeDynaItem (dynamic root object).<br/>
''' This is a generated base class of <see cref="ProductTypeDynaItem"/> business object.
''' </summary>
''' <remarks>
''' This class is an item of <see cref="ProductTypeDynaColl"/> collection.
''' </remarks>
<Serializable>
Public Partial Class ProductTypeDynaItem
Inherits BusinessBase(Of ProductTypeDynaItem)
#Region " Static Fields "
Private Shared _lastId As Integer
#End Region
#Region " Business Properties "
''' <summary>
''' Maintains metadata about <see cref="ProductTypeId"/> property.
''' </summary>
<NotUndoable>
Public Shared ReadOnly ProductTypeIdProperty As PropertyInfo(Of Integer) = RegisterProperty(Of Integer)(Function(p) p.ProductTypeId, "Product Type Id")
''' <summary>
''' Gets the Product Type Id.
''' </summary>
''' <value>The Product Type Id.</value>
Public ReadOnly Property ProductTypeId As Integer
Get
Return GetProperty(ProductTypeIdProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="Name"/> property.
''' </summary>
Public Shared ReadOnly NameProperty As PropertyInfo(Of String) = RegisterProperty(Of String)(Function(p) p.Name, "Name")
''' <summary>
''' Gets or sets the Name.
''' </summary>
''' <value>The Name.</value>
Public Property Name As String
Get
Return GetProperty(NameProperty)
End Get
Set(ByVal value As String)
SetProperty(NameProperty, value)
End Set
End Property
#End Region
#Region " Constructor "
''' <summary>
''' Initializes a new instance of the <see cref="ProductTypeDynaItem"/> class.
''' </summary>
''' <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub New()
' Use factory methods and do not use direct creation.
AddHandler Saved, AddressOf OnProductTypeDynaItemSaved
AddHandler ProductTypeDynaItemSaved, AddressOf ProductTypeDynaItemSavedHandler
End Sub
#End Region
#Region " Cache Invalidation "
'TODO: edit "ProductTypeDynaItem.vb", uncomment the "OnDeserialized" method and add the following line:
'TODO: AddHandler ProductTypeDynaItemSaved, AddressOf ProductTypeDynaItemSavedHandler
Private Sub ProductTypeDynaItemSavedHandler(sender As Object, e As Csla.Core.SavedEventArgs)
'' this runs on the client
ProductTypeCachedList.InvalidateCache()
ProductTypeCachedNVL.InvalidateCache()
End Sub
''' <summary>
''' Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
''' </summary>
''' <param name="e">The DataPortalContext object passed to the DataPortal.</param>
Protected Overrides Sub DataPortal_OnDataPortalInvokeComplete(e As Csla.DataPortalEventArgs)
If ApplicationContext.ExecutionLocation = ApplicationContext.ExecutionLocations.Server AndAlso
e.Operation = DataPortalOperations.Update Then
'' this runs on the server
ProductTypeCachedNVL.InvalidateCache()
End If
End Sub
#End Region
#Region " Data Access "
''' <summary>
''' Loads default values for the <see cref="ProductTypeDynaItem"/> object properties.
''' </summary>
<RunLocal>
Protected Overrides Sub DataPortal_Create()
LoadProperty(ProductTypeIdProperty, System.Threading.Interlocked.Decrement(_lastId))
Dim args As New DataPortalHookArgs()
OnCreate(args)
MyBase.DataPortal_Create()
End Sub
''' <summary>
''' Loads a <see cref="ProductTypeDynaItem"/> object from the given SafeDataReader.
''' </summary>
''' <param name="dr">The SafeDataReader to use.</param>
Private Sub DataPortal_Fetch(dr As SafeDataReader)
' Value properties
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"))
LoadProperty(NameProperty, dr.GetString("Name"))
Dim args As New DataPortalHookArgs(dr)
OnFetchRead(args)
' check all object rules and property rules
BusinessRules.CheckRules()
End Sub
''' <summary>
''' Inserts a new <see cref="ProductTypeDynaItem"/> object in the database.
''' </summary>
<Transactional(TransactionalTypes.TransactionScope)>
Protected Overrides Sub DataPortal_Insert()
Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.InvoicesConnection, False)
Using cmd = New SqlCommand("dbo.AddProductTypeDynaItem", ctx.Connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).Direction = ParameterDirection.Output
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String
Dim args As New DataPortalHookArgs(cmd)
OnInsertPre(args)
cmd.ExecuteNonQuery()
OnInsertPost(args)
LoadProperty(ProductTypeIdProperty, DirectCast(cmd.Parameters("@ProductTypeId").Value, Integer))
End Using
End Using
End Sub
''' <summary>
''' Updates in the database all changes made to the <see cref="ProductTypeDynaItem"/> object.
''' </summary>
<Transactional(TransactionalTypes.TransactionScope)>
Protected Overrides Sub DataPortal_Update()
Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.InvoicesConnection, False)
Using cmd = New SqlCommand("dbo.UpdateProductTypeDynaItem", ctx.Connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String
Dim args As New DataPortalHookArgs(cmd)
OnUpdatePre(args)
cmd.ExecuteNonQuery()
OnUpdatePost(args)
End Using
End Using
End Sub
''' <summary>
''' Self deletes the <see cref="ProductTypeDynaItem"/> object.
''' </summary>
Protected Overrides Sub DataPortal_DeleteSelf()
DataPortal_Delete(ProductTypeId)
End Sub
''' <summary>
''' Deletes the <see cref="ProductTypeDynaItem"/> object from database.
''' </summary>
''' <param name="productTypeId">The delete criteria.</param>
<Transactional(TransactionalTypes.TransactionScope)>
Protected Sub DataPortal_Delete(productTypeId As Integer)
Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.InvoicesConnection, False)
Using cmd = New SqlCommand("dbo.DeleteProductTypeDynaItem", ctx.Connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@ProductTypeId", productTypeId).DbType = DbType.Int32
Dim args As New DataPortalHookArgs(cmd, productTypeId)
OnDeletePre(args)
cmd.ExecuteNonQuery()
OnDeletePost(args)
End Using
End Using
End Sub
#End Region
#Region " Saved Event "
'TODO: edit "ProductTypeDynaItem.vb", uncomment the "OnDeserialized" method and add the following line:
'TODO: AddHandler Saved, AddressOf OnProductTypeDynaItemSaved
Private Sub OnProductTypeDynaItemSaved(sender As Object, e As Csla.Core.SavedEventArgs)
RaiseEvent ProductTypeDynaItemSaved(sender, e)
End Sub
''' <summary> Use this event to signal a <see cref="ProductTypeDynaItem"/> object was saved.</summary>
Public Shared Event ProductTypeDynaItemSaved As EventHandler(Of Csla.Core.SavedEventArgs)
#End Region
#Region " DataPortal Hooks "
''' <summary>
''' Occurs after setting all defaults for object creation.
''' </summary>
Partial Private Sub OnCreate(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
''' </summary>
Partial Private Sub OnDeletePre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Delete, after the delete operation, before Commit().
''' </summary>
Partial Private Sub OnDeletePost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after setting query parameters and before the fetch operation.
''' </summary>
Partial Private Sub OnFetchPre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after the fetch operation (object or collection is fully loaded and set up).
''' </summary>
Partial Private Sub OnFetchPost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after the low level fetch operation, before the data reader is destroyed.
''' </summary>
Partial Private Sub OnFetchRead(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after setting query parameters and before the update operation.
''' </summary>
Partial Private Sub OnUpdatePre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
''' </summary>
Partial Private Sub OnUpdatePost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
''' </summary>
Partial Private Sub OnInsertPre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
''' </summary>
Partial Private Sub OnInsertPost(args As DataPortalHookArgs)
End Sub
#End Region
End Class
End Namespace
|
CslaGenFork/CslaGenFork
|
trunk/CoverageTest/Invoices/Invoices-DbClass-VB/Invoices.Business/ProductTypeDynaItem.Designer.vb
|
Visual Basic
|
mit
| 11,436
|
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.VisualStudio.Editors.MyApplication
Public Class MyApplicationPropertiesBase
''' <summary>
''' Returns the set of files that need to be checked out to change the given property
''' Must be overriden in sub-class
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Overridable Function FilesToCheckOut(ByVal CreateIfNotExist As Boolean) As String()
Return New String() {}
End Function
End Class ' Class MyApplicationPropertiesBase
End Namespace
|
chkn/fsharp
|
vsintegration/src/vs/FsPkgs/FSharp.Project/VB/FSharpPropPage/Common/MyApplicationProperties.vb
|
Visual Basic
|
apache-2.0
| 753
|
Imports System.ComponentModel.DataAnnotations
Imports System.Web.DynamicData
Imports System.Web
Class Children_InsertField
Inherits FieldTemplateUserControl
End Class
|
neozhu/WebFormsScaffolding
|
Samples.VB/DynamicData/FieldTemplates/Children_Insert.ascx.vb
|
Visual Basic
|
apache-2.0
| 186
|
' 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
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PullMemberUp
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp
Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls
<[UseExportProvider]>
Public Class MemberSelectionViewModelTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectAllMemberMakeSelectAllBecomeChecked() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
private double pi => 3.1416;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectAll()
Assert.True(viewModel.SelectAllCheckBoxState)
Assert.False(viewModel.SelectAllCheckBoxThreeStateEnable)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function DeSelectAllMemberMakeSelectAllBecomeEmpty() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
private double pi => 3.1416;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.DeselectAll()
Assert.False(viewModel.SelectAllCheckBoxState)
Assert.False(viewModel.SelectAllCheckBoxThreeStateEnable)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectPublicMembers() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectPublic()
For Each member In viewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.DeclaredAccessibility = Microsoft.CodeAnalysis.Accessibility.Public)
Assert.True(member.IsChecked)
Next
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function TestMemberSelectionViewModelDont_PullDisableItem() As Task
Dim markUp = <Text><![CDATA[
interface Level2Interface
{
}
interface Level1Interface : Level2Interface
{
}
class Level1BaseClass: Level2Interface
{
}
class MyClass : Level1BaseClass, Level1Interface
{
public void G$$oo()
{
}
public double e => 2.717;
public const days = 365;
private double pi => 3.1416;
protected float goldenRadio = 0.618;
internal float gravitational = 6.67e-11;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectAll()
' select an interface, all checkbox of field will be disable
viewModel.UpdateMembersBasedOnDestinationKind(TypeKind.Interface)
' Make sure fields are not pulled to interface
Dim checkedMembers = viewModel.CheckedMembers()
Assert.Empty(checkedMembers.WhereAsArray(Function(analysisResult) analysisResult.Symbol.IsKind(SymbolKind.Field)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)>
Public Async Function SelectDependents() As Task
Dim markUp = <Text><![CDATA[
using System;
class Level1BaseClass
{
}
class MyClass : Level1BaseClass
{
private int i = 100;
private event EventHandler FooEvent;
public void G$$oo()
{
int i = BarBar(e);
What = 1000;
}
public int BarBar(double e)
{
Nested1();
return 1000;
}
private void Nested1()
{
int i = 1000;
gravitational == 1.0;
}
internal float gravitational = 6.67e-11;
private int What {get; set; }
public double e => 2.717;
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp)
viewModel.SelectDependents()
' Dependents of Goo
Assert.True(FindMemberByName("Goo()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("e", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("What", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("BarBar(double)", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("Nested1()", viewModel.Members).IsChecked)
Assert.True(FindMemberByName("gravitational", viewModel.Members).IsChecked)
' Not the depenents of Goo
Assert.False(FindMemberByName("i", viewModel.Members).IsChecked)
Assert.False(FindMemberByName("FooEvent", viewModel.Members).IsChecked)
End Function
Private Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel
Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name))
If (member Is Nothing) Then
Assert.True(False, $"No member called {name} found")
End If
Return member
End Function
Private Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of MemberSelectionViewModel)
Dim workspaceXml =
<Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup.Value %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim doc = workspace.Documents.Single()
Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id)
If (Not doc.CursorPosition.HasValue) Then
Throw New ArgumentException("Missing caret location in document.")
End If
Dim tree = Await workspaceDoc.GetSyntaxTreeAsync()
Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent)
Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member))
Dim membersViewModel = membersInType.SelectAsArray(
Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False})
Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None)
Return New MemberSelectionViewModel(
workspace.GetService(Of IWaitIndicator),
membersViewModel,
memberToDependents)
End Using
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/VisualStudio/Core/Test/CommonControls/MemberSelectionViewModelTests.vb
|
Visual Basic
|
mit
| 9,398
|
' 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.Runtime.CompilerServices
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.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods
Public Class AnonymousTypesEmittedSymbolsTests : Inherits BasicTestBase
<Fact>
Public Sub EmitAnonymousTypeTemplate_NoNeededSymbols()
Dim compilationDef =
<compilation name="EmitAnonymousTypeTemplate_NoNeededSymbols">
<file name="a.vb">
Class ModuleB
Private v1 = New With { .aa = 1 }
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithReferences(sources:=compilationDef, references:={})
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30002: Type 'System.Void' is not defined.
Class ModuleB
~~~~~~~~~~~~~~
BC31091: Import of type 'Object' from assembly or module 'EmitAnonymousTypeTemplate_NoNeededSymbols.dll' failed.
Class ModuleB
~~~~~~~
BC30002: Type 'System.Object' is not defined.
Private v1 = New With { .aa = 1 }
~~
BC30002: Type 'System.Object' is not defined.
Private v1 = New With { .aa = 1 }
~~~~~~~~~~~~~~~~
BC30002: Type 'System.Int32' is not defined.
Private v1 = New With { .aa = 1 }
~
</errors>)
End Sub
<Fact>
Public Sub EmitAnonymousTypeTemplateGenericTest()
Dim compilationDef =
<compilation name="EmitGenericAnonymousTypeTemplate">
<file name="a.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType)
Assert.True(type.IsGenericType)
Assert.Equal(3, type.TypeParameters.Length)
End Sub)
End Sub
<Fact>
Public Sub EmitAnonymousTypeUnification01()
Dim compilationDef =
<compilation name="EmitAnonymousTypeUnification01">
<file name="a.vb">
Module ModuleB
Sub Test1(x As Integer)
Dim at1 As Object = New With { .aa = 1, .b1 = "", .Int = x + x, .Object=Nothing }
Dim at2 As Object = New With { .aA = "X"c, .B1 = 0.123# * x, .int = new Object(), .objecT = Nothing }
at1 = at2
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers()
Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)).ToList()
Assert.Equal(1, list.Count())
Dim type = list.First()
Assert.Equal("VB$AnonymousType_0", type.Name)
Assert.Equal(4, type.Arity)
Dim mems = type.GetMembers()
' 4 fields, 4 get, 4 set, 1 ctor, 1 ToString
Assert.Equal(14, mems.Length)
Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt)
Assert.Equal(0, mlist.Count)
End Sub)
End Sub
<Fact>
Public Sub EmitAnonymousTypeUnification02()
Dim compilationDef =
<compilation name="EmitAnonymousTypeUnification02">
<file name="b.vb">
Imports System
Imports System.Collections.Generic
Class A
Sub Test(p As List(Of String))
Dim local = New Char() {"a"c, "b"c}
Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)}
End Sub
End Class
</file>
<file name="a.vb">
Structure S
Function Test(p As Char()) As Object
Dim at2 As Object = New With {.TEST = New System.Collections.Generic.List(Of String)(), Key .Key = p, Key .K2 = ""}
Return at2
End Function
End Structure
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers()
Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList()
Assert.Equal(1, list.Count())
Dim type = list.First()
Assert.Equal("VB$AnonymousType_0", type.Name)
Assert.Equal(3, type.Arity)
Dim mems = type.GetMembers()
' 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals
Assert.Equal(12, mems.Length)
Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt)
Assert.Equal(3, mlist.Count)
End Sub)
End Sub
<Fact>
Public Sub EmitAnonymousTypeUnification03()
Dim compilationDef =
<compilation name="EmitAnonymousTypeUnification03">
<file name="b.vb">
Imports System
Imports System.Collections.Generic
Class A
Sub Test(p As List(Of String))
Dim local = New Char() {"a"c, "b"c}
Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)}
End Sub
End Class
</file>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Class B
Sub Test(p As List(Of String))
Dim local = New Char() {"a"c, "b"c}
Dim at1 As Object = New With {.test = p, Key .key = local, .k2 = "QC" + p(0)}
End Sub
End Class
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers()
Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList()
' no unification - diff in key
Assert.Equal(2, list.Count())
Dim type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_1").Single()
Assert.Equal("VB$AnonymousType_1", type.Name)
Assert.Equal(3, type.Arity)
Dim mems = type.GetMembers()
' Second: 3 fields, 3 get, 2 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals
Assert.Equal(13, mems.Length)
Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt)
Assert.Equal(3, mlist.Count)
'
type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_0").Single()
Assert.Equal("VB$AnonymousType_0", type.Name)
Assert.Equal(3, type.Arity)
mems = type.GetMembers()
' First: 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals
Assert.Equal(12, mems.Length)
mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt)
Assert.Equal(3, mlist.Count)
End Sub)
End Sub
<Fact>
Public Sub EmitAnonymousTypeCustomModifiers()
Dim compilationDef =
<compilation name="EmitAnonymousTypeCustomModifiers">
<file name="b.vb">
Imports System
Imports System.Collections.Generic
Class A
Sub Test(p As List(Of String))
Dim intArrMod = Modifiers.F9()
Dim at1 = New With { Key .f = intArrMod}
Dim at2 = New With { Key .f = New Integer() {}}
at1 = at2
at2 = at1
End Sub
End Class
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef, TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll})
End Sub
<Fact>
Public Sub AnonymousTypes_MultiplyEmitOfTheSameAssembly()
Dim compilationDef =
<compilation name="AnonymousTypes_MultiplyEmitOfTheSameAssembly">
<file name="b.vb">
Module ModuleB
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1 }
Dim v2 As Object = New With { Key .AA = "a" }
End Sub
End Module
</file>
<file name="a.vb">
Module ModuleA
Sub Test1(x As Integer)
Dim v1 As Object = New With { .Aa = 1 }
Dim v2 As Object = New With { Key .aA = "A" }
End Sub
End Module
</file>
<file name="c.vb">
Module ModuleC
Sub Test1(x As Integer)
Dim v1 As Object = New With { .AA = 1 }
Dim v2 As Object = New With { Key .aa = "A" }
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim position = compilationDef.<file>.Value.IndexOf("Dim v2", StringComparison.Ordinal) - 1
' The sole purpose of this is to check if there will be any asserts
' or exceptions related to adjusted names/locations of anonymous types
' symbols when Emit is called several times for the same compilation
For i = 0 To 10
Using stream As New MemoryStream()
compilation.Emit(stream)
End Using
' do some speculative semantic query
Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB<%= i %> = "" }</text>.Value)
Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression)
Assert.NotNull(info1.Type)
Next
End Sub
<Fact>
Public Sub EmitCompilerGeneratedAttributeTest()
Dim compilationDef =
<compilation name="EmitCompilerGeneratedAttributeTest">
<file name="a.vb">
Module Module1
Sub Test1(x As Integer)
Dim v As Object = New With { .a = 1 }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1")
Assert.NotNull(type)
Dim attr = type.GetAttribute(
GetNamedTypeSymbol(m, "System.Runtime.CompilerServices.CompilerGeneratedAttribute"))
Assert.NotNull(attr)
End Sub)
End Sub
<Fact>
Public Sub CheckPropertyFieldAndAccessorsNamesTest()
Dim compilationDef =
<compilation name="CheckPropertyFieldAndAccessorsNamesTest">
<file name="b.vb">
Module ModuleB
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1 }.aa
Dim v2 As Object = New With { Key .AA = "a" }.aa
End Sub
End Module
</file>
<file name="a.vb">
Module ModuleA
Sub Test1(x As Integer)
Dim v1 As Object = New With { .Aa = 1 }.aa
Dim v2 As Object = New With { Key .aA = "A" }.aa
End Sub
End Module
</file>
<file name="c.vb">
Module ModuleC
Sub Test1(x As Integer)
Dim v1 As Object = New With { .AA = 1 }.aa
Dim v2 As Object = New With { Key .aa = "A" }.aa
End Sub
End Module
</file>
</compilation>
' Cycle to hopefully get different order of files
For i = 0 To 50
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1")
Assert.NotNull(type)
CheckPropertyAccessorsAndField(m, type, "aa", type.TypeParameters(0), False)
type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`1")
Assert.NotNull(type)
CheckPropertyAccessorsAndField(m, type, "AA", type.TypeParameters(0), True)
End Sub)
Next
End Sub
<Fact>
Public Sub CheckEmittedSymbol_ctor()
Dim compilationDef =
<compilation name="CheckEmittedSymbol_ctor">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Assert.Equal(1, type.InstanceConstructors.Length)
Dim constr = type.InstanceConstructors(0)
CheckMethod(m, constr, ".ctor", Accessibility.Public, isSub:=True, paramCount:=3)
Assert.Equal(type.TypeParameters(0), constr.Parameters(0).Type)
Assert.Equal("aa", constr.Parameters(0).Name)
Assert.Equal(type.TypeParameters(1), constr.Parameters(1).Type)
Assert.Equal("BB", constr.Parameters(1).Name)
Assert.Equal(type.TypeParameters(2), constr.Parameters(2).Type)
Assert.Equal("CCC", constr.Parameters(2).Name)
End Sub)
End Sub
<Fact>
Public Sub CheckEmittedSymbol_ToString()
Dim compilationDef =
<compilation name="CheckEmittedSymbol_ToString">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Dim toStr = type.GetMember(Of MethodSymbol)("ToString")
CheckMethod(m, toStr, "ToString", Accessibility.Public,
retType:=GetNamedTypeSymbol(m, "System.String"),
isOverrides:=True, isOverloads:=True)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("ToString"), toStr.OverriddenMethod)
End Sub)
End Sub
<Fact>
Public Sub CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields()
Dim compilationDef =
<compilation name="CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Assert.Equal(0, type.Interfaces.Length)
Assert.Equal(0, type.GetMembers("GetHashCode").Length)
Assert.Equal(0, type.GetMembers("Equals").Length)
End Sub)
End Sub
<Fact>
Public Sub CheckEmittedSymbol_SystemObject_Equals()
Dim compilationDef =
<compilation name="CheckEmittedSymbol_SystemObject_Equals">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Dim method = DirectCast(type.GetMembers("Equals").
Where(Function(s)
Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 0
End Function).Single(),
MethodSymbol)
CheckMethod(m, method, "Equals", Accessibility.Public,
retType:=GetNamedTypeSymbol(m, "System.Boolean"),
isOverrides:=True, isOverloads:=True, paramCount:=1)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), method.Parameters(0).Type)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object").
GetMembers("Equals").Where(Function(s) Not s.IsShared).Single(),
method.OverriddenMethod)
End Sub)
End Sub
<Fact>
Public Sub CheckEmittedSymbol_GetHashCode()
Dim compilationDef =
<compilation name="CheckEmittedSymbol_GetHashCode">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Dim method = type.GetMember(Of MethodSymbol)("GetHashCode")
CheckMethod(m, method, "GetHashCode", Accessibility.Public,
retType:=GetNamedTypeSymbol(m, "System.Int32"),
isOverrides:=True, isOverloads:=True)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("GetHashCode"), method.OverriddenMethod)
End Sub)
End Sub
<Fact>
Public Sub CheckEmittedSymbol_IEquatableImplementation()
Dim compilationDef =
<compilation name="CheckEmittedSymbol_GetHashCode">
<file name="b.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() }
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Assert.Equal(1, type.Interfaces.Length)
Dim [interface] = type.Interfaces(0)
Assert.Equal(GetNamedTypeSymbol(m, "System.IEquatable").Construct(type), [interface])
Dim method = DirectCast(type.GetMembers("Equals").
Where(Function(s)
Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 1
End Function).Single(),
MethodSymbol)
CheckMethod(m, method, "Equals", Accessibility.Public,
retType:=GetNamedTypeSymbol(m, "System.Boolean"), paramCount:=1,
isOverloads:=True)
Assert.Equal(type, method.Parameters(0).Type)
Assert.Equal([interface].GetMember("Equals"), method.ExplicitInterfaceImplementations(0))
End Sub)
End Sub
<Fact>
Public Sub NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI()
Dim compilationDef =
<compilation name="NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI">
<file name="a.vb">
Module ModuleB
Structure SSS
End Structure
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() }
'POSITION
End Sub
End Module
</file>
</compilation>
Dim position = compilationDef.<file>.Value.IndexOf("'POSITION", StringComparison.Ordinal)
CompileAndVerify(compilationDef,
additionalRefs:={SystemCoreRef},
sourceSymbolValidator:=Sub(m As ModuleSymbol)
Dim compilation = m.DeclaringCompilation
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node0 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.AnonymousObjectCreationExpression).AsNode(), ExpressionSyntax)
Dim info0 = model.GetSemanticInfoSummary(node0)
Assert.NotNull(info0.Type)
Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB = "", .CCC = new SSS() }</text>.Value)
Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression)
Assert.NotNull(info1.Type)
Assert.Equal(info0.Type.OriginalDefinition, info1.Type.OriginalDefinition)
Dim expr2 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, Key .BB = "", .CCC = new SSS() }</text>.Value)
Dim info2 = model.GetSpeculativeTypeInfo(position, expr2, SpeculativeBindingOption.BindAsExpression)
Assert.NotNull(info2.Type)
Assert.NotEqual(info0.Type.OriginalDefinition, info2.Type.OriginalDefinition)
End Sub,
symbolValidator:=Sub(m As ModuleSymbol)
Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3")
Assert.NotNull(type)
Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType)
Assert.True(type.IsGenericType)
Assert.Equal(3, type.TypeParameters.Length)
' Only one type should be emitted!!
Dim type2 = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`3")
Assert.Null(type2)
End Sub)
End Sub
<Fact>
<WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")>
Public Sub Bug641639()
Dim moduleDef =
<compilation name="TestModule">
<file name="a.vb">
Module ModuleB
Sub Test1(x As Integer)
Dim v1 As Object = New With { .aa = 1 }
Dim v2 As Object = Function(y as Integer) y + 1
End Sub
End Module
</file>
</compilation>
Dim testModule = CreateCompilationWithMscorlibAndVBRuntime(moduleDef, TestOptions.ReleaseModule)
Dim compilationDef =
<compilation>
<file name="a.vb">
Module ModuleA
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(moduleDef, {testModule.EmitToImageReference()}, TestOptions.ReleaseDll)
Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousDelegate_0<TestModule>", 2).Length)
Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousType_0<TestModule>", 1).Length)
End Sub
#Region "Utils"
Private Shared Sub CheckPropertyAccessorsAndField(m As ModuleSymbol, type As NamedTypeSymbol, propName As String, propType As TypeSymbol, isKey As Boolean)
Dim prop = DirectCast(type.GetMember(propName), PropertySymbol)
Assert.NotNull(prop)
Assert.Equal(propType, prop.Type)
Assert.Equal(propName, prop.Name)
Assert.Equal(propName, prop.MetadataName)
Assert.Equal(Accessibility.Public, prop.DeclaredAccessibility)
Assert.False(prop.IsDefault)
Assert.False(prop.IsMustOverride)
Assert.False(prop.IsNotOverridable)
Assert.False(prop.IsOverridable)
Assert.False(prop.IsOverrides)
Assert.False(prop.IsOverloads)
Assert.Equal(isKey, prop.IsReadOnly)
Assert.False(prop.IsShared)
Assert.False(prop.IsWriteOnly)
Assert.Equal(0, prop.Parameters.Length)
Assert.False(prop.ShadowsExplicitly)
Dim getter = prop.GetMethod
CheckMethod(m, getter, "get_" & prop.Name,
Accessibility.Public,
retType:=getter.ReturnType)
If Not isKey Then
Dim setter = prop.SetMethod
CheckMethod(m, setter, "set_" & prop.Name,
Accessibility.Public,
paramCount:=1,
isSub:=True)
Assert.Equal(propType, setter.Parameters(0).Type)
Else
Assert.Null(prop.SetMethod)
End If
Assert.Equal(0, type.GetMembers("$" & propName).Length)
End Sub
Private Shared Sub CheckMethod(m As ModuleSymbol, method As MethodSymbol,
name As String, accessibility As Accessibility,
Optional paramCount As Integer = 0,
Optional retType As TypeSymbol = Nothing,
Optional isSub As Boolean = False,
Optional isOverloads As Boolean = False,
Optional isOverrides As Boolean = False,
Optional isOverridable As Boolean = False,
Optional isNotOverridable As Boolean = False)
Assert.NotNull(method)
Assert.Equal(name, method.Name)
Assert.Equal(paramCount, method.ParameterCount)
If isSub Then
Assert.Null(retType)
Assert.Equal(GetNamedTypeSymbol(m, "System.Void"), method.ReturnType)
Assert.True(method.IsSub)
End If
If retType IsNot Nothing Then
Assert.False(isSub)
Assert.Equal(retType, method.ReturnType)
Assert.False(method.IsSub)
End If
Assert.Equal(accessibility, method.DeclaredAccessibility)
Assert.Equal(isOverloads, method.IsOverloads)
Assert.Equal(isOverrides, method.IsOverrides)
Assert.Equal(isOverridable, method.IsOverridable)
Assert.Equal(isNotOverridable, method.IsNotOverridable)
Assert.False(method.IsShared)
Assert.False(method.IsMustOverride)
Assert.False(method.IsGenericMethod)
Assert.False(method.ShadowsExplicitly)
End Sub
Private Shared Function GetNamedTypeSymbol(m As ModuleSymbol, namedTypeName As String) As NamedTypeSymbol
Dim nameParts = namedTypeName.Split("."c)
Dim peAssembly = DirectCast(m.ContainingAssembly, PEAssemblySymbol)
Dim nsSymbol As NamespaceSymbol = Nothing
For Each ns In nameParts.Take(nameParts.Length - 1)
nsSymbol = DirectCast(If(nsSymbol Is Nothing,
m.ContainingAssembly.CorLibrary.GlobalNamespace.GetMember(ns),
nsSymbol.GetMember(ns)), NamespaceSymbol)
Next
Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol)
End Function
#End Region
<Fact, WorkItem(1319, "https://github.com/dotnet/roslyn/issues/1319")>
Public Sub MultipleNetmodulesWithAnonymousTypes()
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Class A
Friend o1 As Object = new with { .hello = 1, .world = 2 }
Friend d1 As Object = Function() 1
public shared Function M1() As String
return "Hello, "
End Function
End Class
</file>
</compilation>
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Class B
Inherits A
Friend o2 As Object = new with { .hello = 1, .world = 2 }
Friend d2 As Object = Function() 1
public shared Function M2() As String
return "world!"
End Function
End Class
</file>
</compilation>
Dim compilationDef3 =
<compilation>
<file name="a.vb">
Class Module1
Friend o3 As Object = new with { .hello = 1, .world = 2 }
Friend d3 As Object = Function() 1
public shared Sub Main()
System.Console.Write(A.M1())
System.Console.WriteLine(B.M2())
End Sub
End Class
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib(compilationDef1, options:=TestOptions.ReleaseModule.WithModuleName("A"))
comp1.VerifyDiagnostics()
Dim ref1 = comp1.EmitToImageReference()
Dim comp2 = CreateCompilationWithMscorlibAndReferences(compilationDef2, {ref1}, options:=TestOptions.ReleaseModule.WithModuleName("B"))
comp2.VerifyDiagnostics()
Dim ref2 = comp2.EmitToImageReference()
Dim comp3 = CreateCompilationWithMscorlibAndReferences(compilationDef3, {ref1, ref2}, options:=TestOptions.ReleaseExe.WithModuleName("C"))
comp3.VerifyDiagnostics()
Dim mA = comp3.Assembly.Modules(1)
Assert.Equal("VB$AnonymousType_0<A>`2", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName)
Assert.Equal("VB$AnonymousDelegate_0<A>`1", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName)
Dim mB = comp3.Assembly.Modules(2)
Assert.Equal("VB$AnonymousType_0<B>`2", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName)
Assert.Equal("VB$AnonymousDelegate_0<B>`1", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName)
CompileAndVerify(comp3, expectedOutput:="Hello, world!", symbolValidator:=
Sub(m)
Dim mC = DirectCast(m, PEModuleSymbol)
Assert.Equal("VB$AnonymousType_0`2", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName)
Assert.Equal("VB$AnonymousDelegate_0`1", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName)
End Sub)
End Sub
End Class
End Namespace
|
pdelvo/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb
|
Visual Basic
|
apache-2.0
| 38,178
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy)
Inherits BoundTreeRewriter
Private Function SubstituteMethodForMyBaseOrMyClassCall(receiverOpt As BoundExpression, originalMethodBeingCalled As MethodSymbol) As MethodSymbol
If (originalMethodBeingCalled.IsMetadataVirtual OrElse Me.IsInExpressionLambda) AndAlso
receiverOpt IsNot Nothing AndAlso (receiverOpt.Kind = BoundKind.MyBaseReference OrElse receiverOpt.Kind = BoundKind.MyClassReference) Then
' NOTE: We can only call a virtual method non-virtually if the type of Me reference
' we pass to this method IS or INHERITS FROM the type of the method we want to call;
'
' Thus, for MyBase/MyClass receivers we MAY need to replace
' the method with a wrapper one to be able to call it non-virtually;
'
Dim callingMethodType As TypeSymbol = Me.CurrentMethod.ContainingType
Dim topLevelMethodType As TypeSymbol = Me.TopLevelMethod.ContainingType
If callingMethodType IsNot topLevelMethodType OrElse Me.IsInExpressionLambda Then
Dim newMethod = GetOrCreateMyBaseOrMyClassWrapperFunction(receiverOpt, originalMethodBeingCalled)
' substitute type parameters if needed
If newMethod.IsGenericMethod Then
Debug.Assert(originalMethodBeingCalled.IsGenericMethod)
Dim typeArgs = originalMethodBeingCalled.TypeArguments
Debug.Assert(typeArgs.Length = newMethod.Arity)
Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol
For i = 0 To typeArgs.Length - 1
visitedTypeArgs(i) = VisitType(typeArgs(i))
Next
newMethod = newMethod.Construct(visitedTypeArgs.AsImmutableOrNull())
End If
Return newMethod
End If
End If
Return originalMethodBeingCalled
End Function
Private Function GetOrCreateMyBaseOrMyClassWrapperFunction(receiver As BoundExpression, method As MethodSymbol) As MethodSymbol
Debug.Assert(receiver IsNot Nothing)
Debug.Assert(receiver.IsMyClassReference() OrElse receiver.IsMyBaseReference())
Debug.Assert(method IsNot Nothing)
method = method.ConstructedFrom()
Dim methodWrapper As MethodSymbol = CompilationState.GetMethodWrapper(method)
If methodWrapper IsNot Nothing Then
Return methodWrapper
End If
' Disregarding what was passed as the receiver, we only need to create one wrapper
' method for a method _symbol_ being called. Thus, if topLevelMethod.ContainingType
' overrides the virtual method M1, 'MyClass.M1' will use a wrapper method for
' topLevelMethod.ContainingType.M1 method symbol and 'MyBase.M1' will use
' a wrapper method for topLevelMethod.ContainingType.BaseType.M1 method symbol.
' In case topLevelMethod.ContainingType DOES NOT override M1, both 'MyClass.M1' and
' 'MyBase.M1' will use a wrapper method for topLevelMethod.ContainingType.BaseType.M1.
Dim containingType As NamedTypeSymbol = Me.TopLevelMethod.ContainingType
Dim methodContainingType As NamedTypeSymbol = method.ContainingType
Dim isMyBase As Boolean = Not methodContainingType.Equals(containingType)
Debug.Assert(isMyBase OrElse receiver.Kind = BoundKind.MyClassReference)
Dim syntax As VisualBasicSyntaxNode = Me.CurrentMethod.Syntax
' generate and register wrapper method
Dim wrapperMethodName As String = GeneratedNames.MakeBaseMethodWrapperName(method.Name, isMyBase)
Dim wrapperMethod As New SynthesizedWrapperMethod(DirectCast(containingType, InstanceTypeSymbol), method, wrapperMethodName, syntax)
' register a new method
If Me.CompilationState.ModuleBuilderOpt IsNot Nothing Then
Me.CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(containingType, wrapperMethod)
End If
' generate method body
Dim wrappedMethod As MethodSymbol = wrapperMethod.WrappedMethod
Debug.Assert(wrappedMethod.ConstructedFrom() Is method)
Dim boundArguments(wrapperMethod.ParameterCount - 1) As BoundExpression
For argIndex = 0 To wrapperMethod.ParameterCount - 1
Dim parameterSymbol As ParameterSymbol = wrapperMethod.Parameters(argIndex)
boundArguments(argIndex) = New BoundParameter(syntax, parameterSymbol, isLValue:=parameterSymbol.IsByRef, type:=parameterSymbol.Type)
Next
Dim meParameter As ParameterSymbol = wrapperMethod.MeParameter
Dim newReceiver As BoundExpression = Nothing
If isMyBase Then
newReceiver = New BoundMyBaseReference(syntax, meParameter.Type)
Else
newReceiver = New BoundMyClassReference(syntax, meParameter.Type)
End If
Dim boundCall As New BoundCall(syntax, wrappedMethod, Nothing, newReceiver,
boundArguments.AsImmutableOrNull, Nothing, wrappedMethod.ReturnType)
Dim boundMethodBody As BoundStatement = If(Not wrappedMethod.ReturnType.IsVoidType(),
DirectCast(New BoundReturnStatement(syntax, boundCall, Nothing, Nothing), BoundStatement),
New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(
New BoundExpressionStatement(syntax, boundCall),
New BoundReturnStatement(syntax, Nothing, Nothing, Nothing))))
' add to generated method collection and return
CompilationState.AddMethodWrapper(method, wrapperMethod, boundMethodBody)
Return wrapperMethod
End Function
''' <summary>
''' A method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <remarks>
''' <example>
''' Class A
''' Protected Overridable Sub F(a As Integer)
''' End Sub
''' End Class
'''
''' Class B
''' Inherits A
'''
''' Public Sub M()
''' Dim b As Integer = 1
''' Dim f As System.Action = Sub() MyBase.F(b)
''' End Sub
''' End Class
''' </example>
''' </remarks>
Friend NotInheritable Class SynthesizedWrapperMethod
Inherits SynthesizedMethod
Private ReadOnly _wrappedMethod As MethodSymbol
Private ReadOnly _typeMap As TypeSubstitution
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Private ReadOnly _locations As ImmutableArray(Of Location)
''' <summary>
''' Creates a symbol for a method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <param name="containingType">Type that contains wrapper method.</param>
''' <param name="methodToWrap">Method to wrap</param>
''' <param name="wrapperName">Wrapper method name</param>
''' <param name="syntax">Syntax node.</param>
Friend Sub New(containingType As InstanceTypeSymbol,
methodToWrap As MethodSymbol,
wrapperName As String,
syntax As VisualBasicSyntaxNode)
MyBase.New(syntax, containingType, wrapperName, False)
Me._locations = ImmutableArray.Create(Of Location)(syntax.GetLocation())
Me._typeMap = Nothing
If Not methodToWrap.IsGenericMethod Then
Me._typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty
Me._wrappedMethod = methodToWrap
Else
Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(methodToWrap.OriginalDefinition.TypeParameters, Me, CreateTypeParameter)
Dim typeArgs(Me._typeParameters.Length - 1) As TypeSymbol
For ind = 0 To Me._typeParameters.Length - 1
typeArgs(ind) = Me._typeParameters(ind)
Next
Dim newConstructedWrappedMethod As MethodSymbol = methodToWrap.Construct(typeArgs.AsImmutableOrNull())
Me._typeMap = TypeSubstitution.Create(newConstructedWrappedMethod.OriginalDefinition,
newConstructedWrappedMethod.OriginalDefinition.TypeParameters,
typeArgs.AsImmutableOrNull())
Me._wrappedMethod = newConstructedWrappedMethod
End If
Dim params(Me._wrappedMethod.ParameterCount - 1) As ParameterSymbol
For i = 0 To params.Count - 1
Dim curParam = Me._wrappedMethod.Parameters(i)
params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type.InternalSubstituteTypeParameters(Me._typeMap), curParam)
Next
Me._parameters = params.AsImmutableOrNull()
Me._returnType = Me._wrappedMethod.ReturnType.InternalSubstituteTypeParameters(Me._typeMap)
End Sub
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me._typeMap
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
' Dev11 emits DebuggerNonUserCode. We emit DebuggerHidden to hide the method even if JustMyCode is off.
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute())
End Sub
Public ReadOnly Property WrappedMethod As MethodSymbol
Get
Return Me._wrappedMethod
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
' This is always a method definition, so the type arguments are the same as the type parameters.
If Arity > 0 Then
Return StaticCast(Of TypeSymbol).From(Me.TypeParameters)
Else
Return ImmutableArray(Of TypeSymbol).Empty
End If
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me._wrappedMethod.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Me._wrappedMethod.IsVararg
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Class
End Namespace
|
DanielRosenwasser/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/MethodToClassRewriter/MethodToClassRewriter.MyBaseMyClassWrapper.vb
|
Visual Basic
|
apache-2.0
| 15,103
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.